ListFragment 如何获取 listView?

2022-09-03 09:05:27

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

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

答案 1

当文档保留时:onCreateView

creates and returns the view hierarchy associated with the fragment

因此,由于该方法不会返回,您将无法访问 through 。您可以在回调中获取有效的引用。或者,您可以尝试使用,如果ListViewgetListView()onActivityCreatedv.findViewById(android.R.id.list)ListViewlist_fragment.xml


答案 2

获取列表 从视图中查看,你得到得更早。

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.

推荐