【问题标题】:How do I refer to two listviews in the same layout with @android:id/list?如何使用@android:id/list 引用同一布局中的两个列表视图?
【发布时间】:2014-10-21 09:08:09
【问题描述】:

我正在尝试在同一布局中的两个列表视图上设置两个不同的适配器。在互联网上进行了几次搜索并且这个错误“必须有一个列表视图,其 id 必须是 android.R.id.list”后,我发现我需要将我的列表视图 id 定义为@android:id/list。

我想知道如何引用使用@android:id/list 的两个不同的列表视图?

下面的代码有意义吗?

ListView lv1 = (ListView) findViewById(android.R.id.list);
ListView lv2 = (ListView) findViewById(android.R.id.list);

ps:我正在使用 Fragment 并扩展 ListFragment。

【问题讨论】:

  • 在 xml 文件中给出不同的 id
  • 您必须为此使用自定义适配器。在这种情况下,您无需使用此 id,并且可以用任何东西更改名称。但问题是,你为什么需要它?
  • I am working in a Fragment and extending ListFragment. 这就是问题所在。您最好扩展 Fragment(包含两个具有不同 id 的 ListView),而不是 ListFragment。 OR 使用 2 个不同的 ListFragment,每个都包含自己的 ListView。如您所知,一个 Activity 可以包含多个 Fragment(或派生类)。
  • @Funkystein,谢谢。现在它起作用了。 :)

标签: android android-layout android-listview android-xml android-listfragment


【解决方案1】:

我想知道如何引用使用@android:id/list 的两个不同的列表视图?

简单的答案是不可能(假设两个ListViews 在相同的布局中)。

id @android:id/list 只是在使用ListActivityListFragment 时为ListView 定义资源ID 的一种“方便”方式。

布局中每个小部件的 ID 必须是唯一的,这意味着您应该为 ListViews 定义自己的 ID。

【讨论】:

    【解决方案2】:

    在您的 xml 文件中:

    <ListView
            android:id="@+id/list1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
             >
        </ListView>
    <ListView
            android:id="@+id/list2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
             >
        </ListView>
    

    获取列表视图的引用为:

    ListView lv1 = (ListView) findViewById(R.id.list1);
    ListView lv2 = (ListView) findViewById(R.id.list2);
    

    记住: R.id.list1 不是 android.R.id.list1

    【讨论】:

    • 是的,然后我得到这个错误“must have a listview whos id must be android.R.id.list”。
    • “必须有一个列表视图,其 id 必须是 android.R.id.list” 因为您正在扩展 ListFragment 而不是 Fragment
    • @EdoardoMoreni 清理并构建您的项目
    【解决方案3】:

    在您的 xml 中定义一个自定义 ID:android:id="@+id/yourId" 并使用此新 ID 引用列表

    【讨论】:

    • 我做不到,“必须有一个listview whos id必须是android.R.id.list”。
    • 这个答案是错误的。 Op使用的是ListFragment,ListFragment的约束是ListView的id必须是android.R.id.list
    • “必须有一个列表视图,其 id 必须是 android.R.id.list” 因为您正在扩展 ListFragment 而不是 Fragment
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多