使用 ListFragment 时无法引用 ListView

Unable to reference ListView while using ListFragment

我正在尝试使用 JSON 填充 ListView,但我 运行 在引用 ListView 时遇到了麻烦。

这是我的layout_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp">


<ListView
    android:id="@id/android:list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:drawSelectorOnTop="false" />


<TextView
    android:id="@android:id/empty"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="No data"        />
</LinearLayout>

我在 ListFragment 文档中看到,在设计自定义列表时,我需要将 ListView 的 id 保留为“@id/android:list”。

这是我遇到问题的一段代码:

list = (ListView)getView().findViewById(R.id.list);

我目前在我的 JSON 解析方法中有该代码,但我已尝试根据我在网上阅读的其他建议将其放入我的 public View onCreateView 方法中,但我仍然得到以下信息错误:

Cannot Resolve symbol 'list'

有人能帮我解决问题吗?

list = (ListView)getView().findViewById(R.id.list);

您使用您的应用程序 R 还是 android 的 R?尝试这样编码:

list = (ListView)getView().findViewById(android.R.id.list);

classListFragment里面包含了一个listview和adapter,也提供了一些获取listview并对其进行操作的方法。

可以这样引用(从ListFragment):

getListView()

只有在需要自定义布局时才需要参考android:id="@id/android:list"。在这种情况下你需要覆盖 onCreateView 方法,然后引用列表元素 "@android:id/list"

(ListView)getView().findViewById(android.R.id.list)

getListView() 

是一样的东西。但是你不需要使用第一个表达式,除非你想在 ListFragment

中自定义 ListView