适配器
import ...;
public class CustomAdapter extends ArrayAdapter<MyObject> {
public CustomAdapter(Context context, ArrayList<MyObject> objects) {
super(context, 0, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view1 = inflater.inflate(R.layout.row, parent, false);
MyObject myobj = getItem(position);
String objectName = myobj.getName();
TextView name_TV = (TextView) view1.findViewById(R.id.name);
name_TV.setText(objectName);
return view1;
}
}
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList <MyObject> obj_list = new ArrayList<MyObject>();
obj_list.add(new MyObject("user1", 123));
obj_list.add(new MyObject("user2", 123));
obj_list.add(new MyObject("user3", 123));
CustomAdapter adptr = new CustomerAdapter(this, obj_list);
ListView lv = (ListView) findViewById(R.id.abcListview);
lv.setAdapter(adptr);
}
MyObject类
public class MyObject{
String a;
int b;
public MyObject(String a, int b){
this.a = a;
this.b = b;
}
public String getName(){
return a;
}
}
代码将生成3个列表视图项并打印“user3”三次,而不是一次打印“user1”,一次打印“user2”,一次打印“user3”。
修改 上述代码的结果:http://imgur.com/BBJS0wt
答案 0 :(得分:1)
您应该使用
ViewHolder
范例。
<强> EDITED 强>
问题出在您的getView()
,试试这个:
public static class ViewHolder {
public TextView name;
}
MyObject myobj;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view1 = convertView;
ViewHolder holder;
if (null == view1) {
holder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
view1 = inflater.inflate(R.layout.row, parent, null);
holder.name = (TextView) view1.findViewById(R.id.name);
view1.setTag(holder);
}
else
holder = (ViewHolder) view1.getTag();
myobj = getItem(position);
if (myobj == null)
return view1;
String objectName = myobj.getName();
holder.name.setText(objectName);
return view1;
}
希望这会有所帮助