[英]Android - Fragment findViewById() always null?
Yes, I realize there are questions VERY similar to this one, but unlike the others, my onCreateView()
method inflates the view for the fragment. 是的,我意识到有些问题与该问题非常相似,但是与其他问题不同,我的
onCreateView()
方法扩大了片段的视图。 When I don't use findViewById()
, everything inflates and my app works as expected (except for the functionality for the views I want to get in findViewById()
. 当我不使用
findViewById()
,一切都会膨胀,并且我的应用程序将按预期运行(除了我想在findViewById()
获取的视图的功能之外findViewById()
。
Here is my code: 这是我的代码:
@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);
}
Whenever I want to access a ListView within my layout, I do this: 每当我想访问布局中的ListView时,我都会这样做:
private ListView getListView()
{
return (ListView)getView().findViewById(R.id.main_events);
}
but this is always null. 但这始终为空。 Why?
为什么? My
fragment_main.xml
looks like so: 我的
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>
Use Below Code to inflate your view and get id of listview. 使用下面的代码来扩大您的视图并获取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;
}
Try this,hope this helps 试试这个,希望这会有所帮助
@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.