我有一个自定义的Listview布局,每一行项目都包含一个按钮,当我单击它时,它会在项目中显示一个小的图像视图,但是我在一个项目中执行的操作会重复到列表中的另一个项目,例如,如果我单击项目1中的按钮,图像视图将显示在项目1和项目10中,如果我单击项目2中的按钮,图像视图将显示在项目2和项目11上,而当我滚动它时,它将在不同的项目中重复,以下是我的自定义适配器的代码:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
mparent = parent;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.places_item, parent, false);
holder = new ViewHolder();
holder.placeimage = (CircularImageView) convertView.findViewById(R.id.locationimage_pilayout);
holder.addbtn = (TextView) convertView.findViewById(R.id.addbtn_pilayout);
holder.delbtn = (TextView) convertView.findViewById(R.id.delbtn_pilayout);
holder.oribtn = (TextView) convertView.findViewById(R.id.oribtn_pilayout);
holder.placename = (TextView) convertView.findViewById(R.id.locationname_pilayout);
holder.selected = (ImageView) convertView.findViewById(R.id.selected_pilayout);
holder.origin = (ImageView) convertView.findViewById(R.id.origin_pilayout);
holder.swipeLayout = (SwipeRevealLayout) convertView.findViewById(R.id.swipe_pilayout);
holder.mainLayout = (LinearLayout) convertView.findViewById(R.id.main_pilayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Place item = getItem(position);
/*
my code assigning the button click listener and assigning the views
*/
return convertView;
}
我是不是遗漏了什么?我确信这可能是一个简单的解决方法,但我还没有找到它。如有任何帮助,我们将不胜感激。
发布于 2019-05-21 04:55:59
在ListView
中,可以重用行的各个视图。例如,假设窗口最多可以在ListView
中显示10行。现在,当您向下滚动时,第一个视图从顶部移出窗口,而新的第11个视图从底部进入窗口。为了节省内存和CPU电量,Android在第11个视图中使用了相同的第一个视图。这就是convertView
和if (convertView == null) {} else {}
代码的目的。
因此,图像显示在第一个项目和第11个项目中的原因是,它们恰好是一个视图对象。为了解决这个问题,在getView()
方法中,您需要重置每个视图的每个属性,并且不依赖于默认值。
因此,添加如下所示的一行代码,就可以解决上述问题:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// all your code ...
holder.placeImage.setImageResource(0); //<-- This clears any previously set image.
return convertView;
}
https://stackoverflow.com/questions/56227789
复制相似问题