2011-06-09 51 views
0

我有一個問題,而我動態地嘗試更改微調框時更改佈局。 我需要從onItemSelectedListener方法中找到主視圖。 這裏的代碼從onItemSelectedListener動態修改佈局

public class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
     if (parent.getSelectedItemPosition()==0){//Apertura di un libro 

      LinearLayout lyt_libro = new LinearLayout(getApplicationContext()); 
      lyt_libro.setOrientation(LinearLayout.VERTICAL); 
      //HERE THE PROBLEM. HOW CAN I FIND THE MAIN LAYOUT IN WHICH I CAN ADD THE lyt_libro? 
      final EditText etx_numeroPagine = new EditText(getApplicationContext()); 
      lyt_libro.addView(etx_numeroPagine); 
      [... other stuff....] 
    } 
    public void onNothingSelected(AdapterView parent) { 
     // Do nothing. 
    } 

public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    ScrollView view_mainScroll = new ScrollView(getApplicationContext()); 
    LinearLayout lyt_main = new LinearLayout(getApplicationContext()); 
    view_mainScroll.addView(lyt_main); 
    lyt_main.setOrientation(LinearLayout.VERTICAL); 
    final Spinner spn_selectInterrogationType = new Spinner(getApplicationContext()); 
    lyt_main.addView(spn_selectInterrogationType); 
    final ArrayAdapter<String> spn_selectInterrItemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item); 
    spn_selectInterrItemAdapter.add("Apertura di un libro"); 
    spn_selectInterrItemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    spn_selectInterrogationType.setAdapter(spn_selectInterrItemAdapter); 
    spn_selectInterrogationType.setPrompt("Tipo di metodo utilizzato"); 

    spn_selectInterrogationType.setOnItemSelectedListener(new CustomOnItemSelectedListener()); 
    setContentView(view_mainScroll); 
} 

我評論在那裏我有問題..我可以做些什麼來找到它?我對java和android都很新,所以我有點失落:) 另一個疑問是:使用getApplicationContext()是否正確?從我所瞭解的api文檔中,最好不要使用它,但我不明白如何去做。

非常感謝! :D

編輯: 我從代碼創建所有的佈局,因爲我需要在運行時動態地更改每個元素,所以我需要檢索它與一個函數或類似的東西..與XML我沒有問題,但他們不是我所需要

回答

0

您可以在XML使用的標識符爲主要佈局,並在你的代碼,你可以用findViewById(R.id.name_in_your_xmlFile)發現

還記得投下你所接受的觀點。

0

在您的xml文件中給出一個名稱/ id到將包含您的組件的佈局。

然後通過使用findViewById獲取佈局。

並添加您的看法。

另一種技術可能是在屬性可見性消失的xml文件中聲明字段,並在代碼中響應您的事件,獲取視圖(通過id如上)和setVisilibity獲取View.VISIBLE。

Regards, Stéphane