2011-03-07 47 views
2

我試圖在偵聽器類中處理微調器的onItemSelected事件時通過ID獲取TextView。在我的主要活動中,我可以調用findViewById(R.id.textView1),它工作正常。但是,如果我在我的微調監聽器類中調用相同的函數,它總是返回null並強制應用程序關閉。Android findViewById在主類以外的類中使用時返回null活動

任何人都知道爲什麼findViewById在我的主要Activity中工作,但不在我的偵聽器類中?

這是我主要活動的代碼。點擊一個按鈕,當它被稱爲:

public void something() 
{ 
    setContentView(R.layout.spinnerLayout); 

    Spinner spinner = (Spinner) findViewById(R.id.mySpinner); 
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
      this, R.array.spinner_array, android.R.layout.simple_spinner_item); 
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    spinner.setAdapter(adapter); 

    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); 

} 

這裏是MyOnItemSelectedListener代碼:

public class MyOnItemSelectedListener implements OnItemSelectedListener 
{ 

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
    {    
     TextView tv = view.findViewById(R.id.myTextView); 
     // I want to set the text of this text view to the value selected using the spinner 
     tv.setText("Something"); 
    } 

    public void onNothingSelected(AdapterView parent) { 
     // Do nothing. 
    } 
} 

什麼我需要做的就是「TextView的電視= view.findViewById(R.id .myTextView);」上班?

謝謝!

回答

7

爲了findViewById工作,你必須以前叫setContentView

+1

在我的主Activity中,我已經調用了setContentView(R.layout.somename)。然後佈局顯示微調,當我從列表中選擇一個項目時,我需要它使用findViewById更新TextView。 – Bumper 2011-03-07 17:59:34

+0

對不起,我把「somename」,因爲我沒有我的代碼在我面前,但它確實將內容視圖設置爲微調器所在的佈局。 – Bumper 2011-03-07 18:04:07

+0

粘貼完整的代碼,以便我們可以提供診斷。 – Cristian 2011-03-07 18:09:45

1

你在哪裏設置內容有何看法?當您擴展Activity時,應該有一個方法onCreate,其中您需要setContentView(R.id.textview1)

+0

我只做了listener類擴展Activity,因爲我無法讓view.findViewById()工作。我不知道我是否應該在這裏擴展活動。 – Bumper 2011-03-07 18:01:20

1

如果你有一個setContentView在其他職位提到你可能需要指定在該視圖找到的TextView:

TextView tv = (TextView)view.findViewById (R.id.textView1); 
+0

對不起,我忘了在我的文章中發表演說,但它是在我的實際代碼中。我現在只是將它添加到我的帖子中。 – Bumper 2011-03-07 18:02:22

0

在我的主要活動我可以調用findViewById(R.id .textView1),它工作正常。但是,如果我在我的微調監聽器類中調用相同的函數,它總是返回null並強制應用程序關閉。

由於我是新來的Android得,我可能是錯的,但我有我的想法的幾件事情:

  1. 爲什麼你的聽衆延伸的活動?
  2. 如果你再次調用findByView,android必須再次沿樹找到正確的ID,只要在field變量中找到它就保存textView
  3. 如果這真的是一個活動,你是否激發了正確的意圖在你的主要活動中啓動它?
  4. 您是否將該活動添加到manifest.xml?
  5. ......正如其他人所說,這可能是錯誤的背景。

更多的代碼片段會很好。 nyyrikki