简体   繁体   中英

Change Listview item background

As Adapter for ListView, I am using custom adapter. On Adapter's getView method, I am trying to change listitem's background image using setBackgroundDrawable.

public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        CurrencyModel currency = new CurrencyModel();
        currency = currencyList.get(position);

        if (convertView == null) {
            vi = inflater.inflate(R.layout.listitem_currency, null);
        }

        TextView tvSymbol = (TextView) vi.findViewById(R.id.tvSymbol);
        TextView tvSize = (TextView) vi.findViewById(R.id.tvSize);
        TextView tvName = (TextView) vi.findViewById(R.id.tvName);
        TextView tvRate = (TextView) vi.findViewById(R.id.tvRate);

        tvSymbol.setText(currency.getSymbol());
        tvSize.setText(currency.getSize());
        tvName.setText(currency.getName());
        tvRate.setText(currency.getRate());

        if (currency.getSymbol().equals("AUD")) {
            vi.setBackgroundDrawable(context.getResources().getDrawable(
                    R.drawable.bg_exch_high_cell));
        }

        return vi;
    }

When activity starts, everything is working correctly - listitem with AUD has different background. All mystery starts when I scroll the listview - other listitems also get "special" background. The more scroll, the more listitems changed. I do not have idea why this is happening. How to solve this problem?

在此处输入图片说明

if (currency.getSymbol().equals("AUD")) {
    vi.setBackgroundDrawable(context.getResources().getDrawable(
                R.drawable.bg_exch_high_cell));
}
else {//restore default background}

This happens because cell views are reused by listview. You should restore default background for other items.

More about list view performance

TextView tvSymbol = (TextView) vi.findViewById(R.id.tvSymbol);

Before this line add the default background the you put to the item. The reason in your code why it happens is that android try using the the already created view(vi). Since if it is assigned bg_exch_high_cell, it will retain it. So reset it in the beginning.

vi.setBackgroundDrawable(context.getResources().getDrawable(
                //default background drawable here ));
TextView tvSymbol = (TextView) vi.findViewById(R.id.tvSymbol);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM