2014-10-28 87 views
0

是的,我意識到有非常類似於這個問題,但不像其他人,我的onCreateView()方法膨脹的片段的看法。當我不使用findViewById(),一切膨脹和預期我的應用程序工作(除了因爲我想在findViewById()得到的意見的功能Android - 片段findViewById()總是空?

這裏是我的代碼:

@Override 
public View onCreateView(LayoutInflater p_inflater, ViewGroup p_container, Bundle p_prev_state) 
{ 
    return p_inflater.inflate(R.layout.fragment_main, p_container, false); 
} 

每當我想我的佈局中訪問一個ListView,我這樣做:

private ListView getListView() 
{ 
    return (ListView)getView().findViewById(R.id.main_events); 
} 

,但這始終是空爲什麼我fragment_main.xml看起來像這樣:?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/white" 
    tools:context="me.k.cal.MainActivity$PlaceholderFragment" > 

    <ListView android:id="@+id/main_events" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:dividerHeight="1dp" 
     android:divider="@color/background_color" /> 

</RelativeLayout> 

My full fragment code can be found here.

+0

'findViewById'可以在片段的view..So被連接,你需要使用它作爲'view.findViewById' – 2014-10-28 05:33:58

+0

那到底什麼時候你調用'getListView()'或調用它的方法,關於片段生命週期? – laalto 2014-10-28 06:23:14

回答

4

使用下面的代碼膨脹你的觀點,並得到ListView控件的ID。

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {                                                               
    View _view = inflater.inflate(R.layout.fragment1, container, false); 

    ListView _list= (ListView) _view.findViewById(R.id.main_events); 
    return _view; 
} 
+0

感謝您的回覆,並對我的反應遲鈍表示歉意。當我運行這個時,'_list'視圖仍然爲空...'onCreateView()'代替了ctor嗎? – 2014-10-29 18:31:47

+0

發佈完整的活動代碼。 – Dev 2014-10-30 04:55:24

+0

我認爲你的佈局是在活動XML中,你正在從片段訪問它。 – Dev 2014-10-30 04:56:09

0

試試這個,希望這有助於

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    if (container == null) { 
     return null; 
    } 
    View view = inflater.inflate(R.layout.fragment_main, container, 
      false); 

    ListView eventsList= (ListView) view.findViewById(R.id.main_events); 

return view; 

}