[英]Android ListView actions repeat in different items
我有一個用於Listview的自定義布局,每個行項目都包含一個按鈕,當單擊該按鈕時,該按鈕在項目中顯示一個小imageview,但是我在一個項目中執行的操作會重復執行列表中的另一個項目,例如,如果我單擊項目1中的按鈕,imageview將顯示在項目1和項目10中,如果我單擊項目2中的按鈕,Imageview將顯示在項目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;
}
我想念什么嗎? 我肯定這可能是一個簡單的修復,但我還沒有找到它。 任何幫助將不勝感激。
在ListView
中,行的各個視圖將被重用。 例如,假設該窗口最多可以在ListView
顯示10行。 現在,當您向下滾動時,第一個視圖從頂部移出窗口,而新的第11個視圖從底部移入窗口。 為了節省內存和CPU能力,Android將相同的1st視圖用於11th視圖。 這就是convertView
和if (convertView == null) {} else {}
代碼的目的。
因此,在第1項和第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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.