Ken*_*den 0 java xml android android-fragments
是的,我意识到有些问题与这个问题非常相似,但与其他问题不同的是,我的onCreateView()方法夸大了片段的视图。当我不使用 时findViewById(),一切都会膨胀,我的应用程序按预期工作(除了我想要进入的视图功能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);
}
Run Code Online (Sandbox Code Playgroud)
每当我想访问布局中的 ListView 时,我都会这样做:
private ListView getListView()
{
return (ListView)getView().findViewById(R.id.main_events);
}
Run Code Online (Sandbox Code Playgroud)
但这始终为空。为什么?我的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>
Run Code Online (Sandbox Code Playgroud)
使用下面的代码来扩充您的视图并获取列表视图的 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;
}
Run Code Online (Sandbox Code Playgroud)