0

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?

enter image description here

2 Answers 2

1
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

1
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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.