android - 使用 ListFragment 时无法引用 ListView

标签 android listview android-fragments android-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'

有人能帮我解决问题吗?

最佳答案

ListFragment 类在其中包含了一个 ListView 和适配器,还提供了一些方法让您可以获取 ListView 并对其进行操作。

您可以通过这种方式(从 ListFragment 中)引用它:

getListView()

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

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

getListView() 

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

中自定义 ListView

关于android - 使用 ListFragment 时无法引用 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31521391/

相关文章:

android - Google Play 控制台中的 "Resubscribe not available"警告消息

c++ - 像 ListView 这样的资源管理器

android - SwipeRefreshLayout 刷新与 fragmentTransactions 冲突

java - 在 Alert Dialog Builder 中编辑文本

java - 显示相同的 Android fragment 两次并使用调用 getById

android - 辅助功能和 Android WebView

android - 动态设置微调器的选择,不触发 OnItemSelectedListener

android - 如何在修改数组后更新 ListView 中的项目

wpf - TabControl WPF 中性能不佳的 ListView

java - 带有复选框的动态 ListView 问题?