java ListFragment 如何获取listView?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10664940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ListFragment how to get the listView?
提问by membersound
I'm porting my app from AsyncTasks to Fragements.
我正在将我的应用程序从 AsyncTasks 移植到 Fragments。
But how can I access the listView (id: list) element within my fragment?
但是如何访问片段中的 listView (id: list) 元素?
class MyFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_fragment, container, false);
ListView listView = getListView(); //EX:
listView.setTextFilterEnabled(true);
registerForContextMenu(listView);
return v;
}
}
xml:
xml:
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
Ex:
前任:
Caused by: java.lang.IllegalStateException: Content view not yet created
回答by Blackbelt
as the onCreateView
doc stays:
由于onCreateView
文档保持不变:
creates and returns the view hierarchy associated with the fragment
so since the method does not return, you will are not able to access the ListView
through getListView()
. You can obtain a valid reference in the onActivityCreated
callback.
Or you can try using v.findViewById(android.R.id.list)
if the ListView
is declared inside list_fragment.xml
因此,由于该方法不返回,您将无法访问ListView
through getListView()
。您可以在onActivityCreated
回调中获得有效的引用。或者你可以尝试使用v.findViewById(android.R.id.list)
ifListView
是在里面声明的list_fragment.xml
回答by Pratap Singh
get list View from the view, you are getting earlier.
从视图中获取列表视图,您越来越早了。
View view = inflater.inflate(android.R.layout.list_content, null);
ListView ls = (ListView) view.findViewById(android.R.id.list);
// do whatever you want to with list.
回答by Subin Sebastian
The easiest and more reliable solution to this problem will be to override onActivityCreated(); and do your list manipulations there.
这个问题最简单、更可靠的解决方案是覆盖 onActivityCreated(); 并在那里进行列表操作。
@Override
public void onActivityCreated(Bundle savedInstanceState) {
ListView listView = getListView(); //EX:
listView.setTextFilterEnabled(true);
registerForContextMenu(listView);
super.onActivityCreated(savedInstanceState);
}
回答by TombMedia
I was able to access the ListView by the OnViewCreated method instead.
我可以通过 OnViewCreated 方法访问 ListView。
回答by Felipe Constantino
ListFragment listFrag = new ListFragment(){
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView list = getListView();
// DO THINGS WITH LIST
}
};