如何使用 ArrayAdapter<myClass> [英] How to use ArrayAdapter<myClass>
本文介绍了如何使用 ArrayAdapter<myClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ArrayList<MyClass> myList = new ArrayList<MyClass>();
ListView listView = (ListView) findViewById(R.id.list);
ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this, R.layout.row,
to, myList.);
listView.setAdapter(adapter);
班级:我的班级
class MyClass {
public String reason;
public long long_val;
}
我在布局中创建了 row.xml,但不知道如何使用 ArrayAdapter 在 ListView 中同时显示 reason 和 long_val.
I have created row.xml in layouts, but don't know how to show both reason and long_val in the ListView using ArrayAdapter.
推荐答案
为您的类实现自定义适配器:
Implement custom adapter for your class:
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}
对于那些不太熟悉 Android 框架的人,这里有更详细的解释:https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.
For those not very familiar with the Android framework, this is explained in better detail here: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.
这篇关于如何使用 ArrayAdapter<myClass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文