如果适配器是对象类型,如何在列表视图中显示对象的 ID

How to show id of an object in listview if the adapter is of type object

所以我有一个 class:

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

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

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 class 中的 toString 方法。

class student{
    public int id;
    public String name;

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

您只需要覆盖 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;
        }
    };