【问题标题】:How to select one value of a JSON to display on ListView using ArrayAdapter如何使用 ArrayAdapter 选择一个 JSON 值在 ListView 上显示
【发布时间】:2015-01-09 02:11:32
【问题描述】:

目前我的 ListView 显示如下:

对象[id=1,名称=对象 1,...]

对象[id=2, name=对象 2, ...]

对象[id=3, name=对象 3, ...]

List<Object> listObject = getObjectListFromJson(jSonObjects);


ArrayAdapter<Object> objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listObject);

我只想显示 JSON 的“名称”值,例如:

对象 1

对象 2

对象 3

我需要编写一个自定义适配器还是有办法使用默认适配器获取“名称”变量?

抱歉,我是 Android 开发和 stackoverflow 的初学者。如果您需要更多信息,请询问我。

【问题讨论】:

  • 这是什么类型的对象,Json?
  • 你也是 StackOverflow 的初学者!欢迎!你的问题对我来说有点道理。也许编辑它也会对其他人有所帮助。看看这个-stackoverflow.com/editing-help
  • @Rohit5k2 是的,JSON。
  • @Rachcha 我打算放图像等,但我缺乏执行这些操作的声誉:)

标签: android json listview android-listview android-arrayadapter


【解决方案1】:

之后

List<Object> listObject = getObjectListFromJson(jSonObjects);

List<String> nameList = new ArrayList<String>();

for (int i=0; i<listObject.size(); i++) {
    nameList.add(listObject.get(i).name); // Change ".name" to the appropriate way to get the name of the object. It depends on the object
}

改变

ArrayAdapter<Object> objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listObject);

ArrayAdapter<String> objectArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, nameList);

【讨论】:

  • 我相信这会奏效,我已经实现了它,但还没有测试,因为我在模拟器上遇到了困难。我已经下载了 Intel HAXM,但仍然需要很长时间才能加载。
  • 没问题。慢慢来。请记住正确获取 name 属性,因为您说它是 Json 对象
  • 是的,我确实记得。它按我想要的方式工作。现在我需要看看如何使用 onClick 方法将数据传递给另一个使用 Intent 的活动:)
【解决方案2】:

如果您有 getObjectListFromJson 创建一些自定义对象类型来保存 ID 和名称,那么您需要做的就是在该类上添加一个 toString 方法以返回名称部分。例如:

class MyObject {
    long id;
    String name;
    public String toString() { return name; }
}

List<MyObject> listObject = getObjectListFromJson(jSonObjects);


ArrayAdapter<MyObject> objectArrayAdapter = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listObject);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    相关资源
    最近更新 更多