2012-09-07 78 views
0

承認可能重複:
findViewById in fragment androidfindViewById不ListFragment

我目前工作的Android項目,並試圖讓碎片的工作。片段部分工作,但我想控制UI組件,在一個標準的活動,我可以使用類似

TextView txtMyTextBox = (TextView)findViewById(R.id.my_text_box) 

我被ListFragment擴展類,但是當我爲什麼嘗試相同的代碼上面,我得到以下錯誤

的方法findViewById(INT)是未定義

爲什麼不這項工作。感謝您的任何幫助,您可以提供。

回答

5

這種方法不能在該片段中類,這是在那裏我假設你調用它來定義。你必須在Fragment顯示的視圖上使用它。這與您在onCreateView()中返回的視圖相同,您可以通過getView()檢索它。因此,TextView txtMyTextBox = (TextView)getView().findViewById(R.id.my_text_box)應該工作。

0

當您使用片段時,您應該重寫onCreateView方法。

這裏是個例:

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     View v = inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, null); 

     TextView txtMyTextBox = (TextView)v.findViewById(R.id.my_text_box) 

     return v; 
    }