【问题标题】:Android setting more than one adapter to one listviewAndroid 将多个适配器设置为一个列表视图
【发布时间】:2015-07-20 06:49:49
【问题描述】:

我有 2 个适配器,每个适配器都包含我想放入一个列表视图的不同 API。如何在不更换第一个适配器的情况下设置第二个适配器?谢谢之前:)

pcAPI = (ArrayList<ListAPI>) parsepcAPI(pcTemp);
artistAPI = (ArrayList<ListAPI>) parseArtistAPI(artistTemp);

lvAPI = (ListView) findViewById(R.id.lvAPI);

Song_APIAdapter adapter = new Song_APIAdapter(getApplicationContext(), pcAPI);
lvAPI.setAdapter(adapter);

Song_APIAdapter adapter2 = new Song_APIAdapter(getApplicationContext(), artistAPI);
lvAPI.setAdapter(adapter2);

【问题讨论】:

  • 你能描述一下适配器的内容有哪些可能有解决办法吗?
  • 在pcAPI和artistAPI中添加项目并调用adapter.notifyDataSetChanged();
  • 如果你想显示来自 两个不同 api 的数据,那么你可以做的是 merge one arraylist 中的两个数据,然后使用一个adpater只有你可以显示两个api数据。
  • @Raghunandan 他们是音乐 api 数据,比如艺术家的名字、歌曲和播放次数。

标签: android android-listview


【解决方案1】:

试试这段代码,它将合并适配器

    Song_APIAdapter adapter = new Song_APIAdapter(getApplicationContext(), pcAPI);
    lvAPI.setAdapter(adapter);
    Song_APIAdapter adapter2 = new Song_APIAdapter(getApplicationContext(), artistAPI);
    adapter.addAdapter(adapter2);

【讨论】:

    【解决方案2】:

    尝试像这样将 2 个适配器合并为一个适配器:

    android attaching multiple adapters to one adapter

    或者,您可以将两个ArrayLists 合并为一个,然后设置Adapter。实际上,这就是您正在做的事情。

    或者您可以先将pcAPI 设置到适配器中,然后将artistAPI 添加到pcAPI,然后再次设置新的适配器。并致电adapter.notifyDataSetChanged()

    为什么你不能简单地做到这一点?

    pcAPI = (ArrayList<ListAPI>) parsepcAPI(pcTemp);
    artistAPI = (ArrayList<ListAPI>) parseArtistAPI(artistTemp);
    
    ArrayList<ListAPI> mergedList = new ArrayList<ListAPI>();
    mergedList.addAll(pcAPI);
    mergedList.add(artistAPI);
    
    Song_APIAdapter adapter = new Song_APIAdapter(getApplicationContext(), mergedAPI);
    lvAPI.setAdapter(adapter);
    

    【讨论】:

    • 非常感谢它的工作:) 我是 android 新手,经常感到困惑哈哈
    • 我很高兴它做到了。如果它解决了您的问题,您可以将答案标记为已接受。这也有助于未来的用户。谢谢。
    【解决方案3】:

    通常,您不应为 1 个列表视图使用 2 个适配器。 Adatper 是将数据转换为视图的接口。

    在您的情况下,您的列表视图显示了 2 种数据。所以你应该创建一个全新的适配器,从 pcAPI 和 ArtistAPI 读取数据,然后生成一个新视图并将其传递给 ListView。

    如果你只需要交替显示pcView和artistView,有一个简单的方法:

    1. 创建一个新的适配器,并将adapter和adapter2传递给它。

    2. 覆盖getCount(),getCount = adapter.getCount()+adapter2.getCount();

    3. 覆盖getView,奇数项返回adapter.getView(...),偶数项返回adapter2.getCount();

    我不知道你想要什么样的视图,所以我只是猜测你的要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多