【问题标题】:How to show id of an object in listview if the adapter is of type object如果适配器是对象类型,如何在列表视图中显示对象的 ID
【发布时间】:2015-12-10 11:28:28
【问题描述】:

所以我有课:

class student{
 public int id;
 public String name;
}

然后我有一个学生类型的适配器数组,并且该适配器被传递给列表视图。我想知道如何让列表视图只显示学生的姓名。 代码:

ListView list=(ListView)findViewById(R.id.list_day_wise_expense);
ArrayAdapter<Student> adapter = new ArrayAdapter<Student>( this,R.layout.increase_size_text, kids);
list.setAdapter(adapter);

其中kids 是Student 对象的数组,而list 是我的列表视图。 我希望列表显示他们的名字。

【问题讨论】:

  • 使用应返回您的 Student 类的 adapter.getItem(position) 。然后你可以对其执行 student.name 或 getName() 。
  • 查看tutorial

标签: android listview android-listview


【解决方案1】:

覆盖Student 类中的toString 方法。

class student{
    public int id;
    public String name;

    @Override
    public String toString() {
        return name;
    }
}

【讨论】:

    【解决方案2】:

    你只需要重写 getView()

        ArrayAdapter<Student> adapter = new ArrayAdapter<Student>(this, R.layout.increase_size_text, kids){
            @Override
            public View getView (int position, View convertView, ViewGroup parent) {
                View view = convertView == null ?
                        super.getView(position, convertView, parent) : convertView;
                TextView tv = (TextView) view.findViewById(R.id./* PUT ID HERE */);
                tv.setText(getItem(position).name);
                return view;
            }
        };
    

    而且您不需要创建自己的布局。这也可以:

        ArrayAdapter<Student> adapter = new ArrayAdapter<Student>(this, android.R.layout.simple_list_item_1, kids){
            @Override
            public View getView (int position, View convertView, ViewGroup parent) {
                View view = convertView == null ?
                        super.getView(position, convertView, parent) : convertView;
                TextView tv = (TextView) view.findViewById(android.R.id.text1);
                tv.setText(getItem(position).name);
                return view;
            }
        };
    

    【讨论】:

    • @pskink 取决于你想要 toString() 做什么。有时更可取的是 toString() 实际打印出所有变量。很多时候,您也无法访问该课程。
    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多