开发者

ListView selection issue...Using onItemClick(AdapterView<?> parent, View view, ...)

The problem I hope to resolve h开发者_JAVA百科ere is that when I click on one item in the ListView that item's background changes to light gray, but when I continue to scroll through the list every 4th item has the background changed to light gray even though those other items have not been clicked. How do I make only the item I clicked be effected by the click?

    ListView lv = (ListView) findViewById(R.id.resultsList);
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.resultitem, (String[])labelList.toArray(new String[labelList.size()])));

    lv.setOnItemClickListener(new OnItemClickListener() {    

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {      
            TextView tv = (TextView)view.findViewById(R.id.result);
            tv.setBackgroundColor(Color.LTGRAY);
            tv.setTextColor(Color.BLACK);
        }
     }


You'll have to override getView() in a subclass of ListAdapter, in this case, ArrayAdapter.

This is because Android actually reuses rows to conserve resources and CPU (when a row is scrolled off the screen, it is reused for new rows that come into view). So, if you set the background grey on one row, it'll probably end up being used again, and the background will still be grey.

If you subclass ArrayAdapter, you can have your onItemClickListener set some sort of flag, and then your ArrayAdapter's getView(), you can set the appropriate background color based on the flag.

This link has an example of subclassing ArrayAdapter


I suppose you are using convert view just like this

...public View getView(int position, View convertView, ViewGroup parent) { ....

and you are changing its background at 4th position, and your view let says have 6 rows on one page, so every 4th row of every page will be grayed out because of reusing the same convertView .

I don't know that I am explaining right, but if you are using convertview and changing its layout, so you should have logic to re-create that layout again to avoid re-using same (cached) view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜