java-为什么滚动浏览列表时会重新排序?
作者:互联网
滚动浏览列表时,列表会重新排序..这非常令人困惑.
这是我正在使用的自定义适配器:
public class LoadExpenseList extends BaseAdapter{
List<Expense> expenses;
Context context;
public LoadExpenseList(Context context, int textViewResourceId,
List<Expense> expenses) {
super();
this.expenses = expenses;
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent){
//View v = convertView;
AvailableExpenseView btv;
if (convertView == null) {
btv = new AvailableExpenseView(context, expenses.get(position));
} else {
btv = (AvailableExpenseView) convertView;
}
btv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Expense_Availables", "Item Selected!!");
Intent intent = new Intent(getActivity(), ItemDetailActivity.class);
int id = expenses.get(position).getExpenseItemId();
intent.putExtra("id", id);
startActivity(intent);
}
});
btv.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
return false;
}
});
registerForContextMenu(btv);
return btv;
}
@Override
public int getCount() {
return expenses.size();
}
@Override
public Object getItem(int position) {
return expenses.get(position);
}
@Override
public long getItemId(int position) {
return expenses.get(position).getExpenseItemId();
}
}
解决方法:
因为您的视图(AvailableExpenseView)是用一个项目构造的,所以当适配器尝试通过convertView重用视图时,您将获得一个已经绑定到另一个项目的视图.
不要用模型项构造视图,而是调用诸如convertView.setExpense(expenses.get(position))之类的东西.
ListView将尝试重用视图以提高性能.因此,将发生的事是,列表中的第一项与新创建的视图一起显示,随后在您滚动时,它将尝试重用以前创建的视图,并通过convertView提供视图.请注意以下几行:
if (convertView == null) {
// You create a view using the proper item
btv = new AvailableExpenseView(context, expenses.get(position));
} else {
// You don't override the item that was previously assigned
// when the view was created
btv = (AvailableExpenseView) convertView;
}
如果convertView为null,则说明您正在创建一个新视图,但是要使用一个项目来构造视图.因此,我们假设此位置为0.您将使用列表中第一个的费用创建一个视图.稍后,listView想要获取位置20的视图,并说“确定,让我们重新使用我们用于位置0的视图”,因此它将该视图作为convertView传递,但是此视图已经在位置0处创建了该视图.并且您不会覆盖它.因此,您最终使用的视图具有第一个项目代表第20个项目.
要解决此问题,您可以轻松地执行以下操作:
AvailableExpenseView btv;
if (convertView == null) {
// dont create your view with an item
btv = new AvailableExpenseView(context);
} else {
btv = (AvailableExpenseView) convertView;
}
// Assign the expense wether it is a newly created view or
// a view that is reused
btv.setExpense(expenses.get(position));
当然,您将必须编辑AvailableExpenseView并创建一个setExpense()方法来填充视图.
标签:listview,baseadapter,java,android 来源: https://codeday.me/bug/20191101/1986740.html