Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the background color of a specific item in listview by position?

I want to set the background color of a specific item in the listview.

My listview is generated by ArrayAdapter using a ArrayList.

I have a specific item in the listview that I plan to change the background color.

I know the item's position in the list.

This is my code for generating the listview.

respondMessageListView = (ListView) findViewById(R.id.respondMessageListView);
respondMessageListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, autoRespondMessages.getMessages()));

Thank you!

[edit]

According to this post, using setSelection makes no effect if is used in onCreate(), the work around is "remove the method onAttachedToWindow in PullToRefreshListView". I am not quite understanding the solution. May I ask how should I accomplish this? I am a subclass of Activity, so I cannot subclass any other class anymore.

like image 599
ssgao Avatar asked Nov 04 '22 15:11

ssgao


1 Answers

You will have to subclass ArrayAdapter and override the getView(...) method. For simplicity's sake you could just call through to the base class implementation and set the background color for the returned View.

Edit: The following example colors the items' backgrounds alternating black and white.

private class MyAdapter extends ArrayAdapter {

    ...

    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);
        v.setBackgroundColor(position % 2 == 0 : 0xff000000, 0xffffffff);
    }
}
like image 56
zienkikk Avatar answered Nov 08 '22 10:11

zienkikk