簡體   English   中英

Android-自定義ListView Viewholder

[英]Android - Custom ListView Viewholder

我試圖在自定義Listview中顯示詳細的產品信息,其中鍵/值對每行有兩個TextView。 數據顯示正確。 我每隔兩行也塗上不同的顏色。

還有我的問題。 如果我上下滾動,則不同顏色的行會更改其顏色並保持這種狀態。 數據不受此問題的影響。 只是TextViews的背景色。 我使用了ViewHolder模式,但這並沒有改變任何東西。 我添加了適配器的代碼。 我認為就足夠了。 你有什么主意嗎

問題的屏幕截圖:

在此處輸入圖片說明

碼:

public class ProductDetailAdapter extends BaseAdapter {

private LinkedHashMap<String,String> list;
private Context context;

public ProductDetailAdapter(Context c, LinkedHashMap<String,String> list){
    super();
    this.context = c;
    this.list=list;

}
@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return list.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    ProductDetailAdapter.ViewHolder viewHolder;

    if(convertView == null){
        convertView=inflater.inflate(R.layout.product_detail_data_row,null);
        viewHolder = new ViewHolder();
        viewHolder.textViewKey = (TextView) convertView.findViewById(R.id.productDataKey);
        viewHolder.textViewValue = (TextView) convertView.findViewById(R.id.productDataValue);
        convertView.setTag(viewHolder);

    }else {
        viewHolder = (ProductDetailAdapter.ViewHolder) convertView.getTag();
    }

    viewHolder.textViewKey.setText((String)list.keySet().toArray()[position]);
    viewHolder.textViewValue.setText(list.get(list.keySet().toArray()[position]));

    if(position % 2 == 0){
        viewHolder.textViewKey.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite2));
        viewHolder.textViewValue.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite2));
    }

    return convertView;
}

private static class ViewHolder {

    public TextView textViewKey;
    public TextView textViewValue;

    public ViewHolder(){};

}
}

發生這種情況是因為行被回收了。 這是一個普遍的問題。

您可以通過以下方法解決此問題:

if(position % 2 == 0){
    viewHolder.textViewKey.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite2));
    viewHolder.textViewValue.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite2));
} else {
    viewHolder.textViewKey.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite1)); //Or the color that you want for odd rows
    viewHolder.textViewValue.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite1)); //Or the color that you want for odd rows
}

嘗試這個:

super( c, 0, list );

代替這個:

super();

將數據源傳遞到適配器后,您將不再需要:

getCount

getItem

getItemId

請參考此鏈接以及link2link3這些將為您工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM