【发布时间】:2014-12-23 10:32:53
【问题描述】:
是的,我意识到有些问题与这个问题非常相似,但与其他问题不同的是,我的 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);
}
每当我想访问布局中的 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>
【问题讨论】:
-
findViewById可以附加一个视图。所以在 Fragment 中,你需要使用它作为view.findViewById -
关于片段生命周期,您究竟何时调用
getListView()或调用它的方法?
标签: java android xml android-fragments