15

我正在将我的应用程序从 AsyncTasks 移植到 Fragments。

但是如何访问我的片段中的 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:

        <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

前任:

Caused by: java.lang.IllegalStateException: Content view not yet created
4

5 回答 5

28

正如onCreateView医生留下的:

creates and returns the view hierarchy associated with the fragment

因此,由于该方法没有返回,您将无法访问ListViewthrough getListView()onActivityCreated您可以在回调中获取有效的引用。或者你可以尝试使用v.findViewById(android.R.id.list)如果在ListView里面声明list_fragment.xml

于 2012-05-19T11:58:31.907 回答
7

从视图中获取列表视图,您越来越早了。

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.
于 2012-12-01T12:50:47.490 回答
4

这个问题最简单和更可靠的解决方案是覆盖 onActivityCreated(); 并在那里进行列表操作。

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    ListView listView = getListView(); //EX: 
    listView.setTextFilterEnabled(true);
    registerForContextMenu(listView);
    super.onActivityCreated(savedInstanceState);
}
于 2013-09-23T17:37:22.003 回答
3

我可以通过 OnViewCreated 方法访问 ListView。

于 2013-05-02T20:29:04.893 回答
1
ListFragment listFrag = new ListFragment(){
        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            ListView list = getListView();
            // DO THINGS WITH LIST
        }
    };
于 2015-04-02T18:56:23.343 回答