How to set the background color for a specific item in the list by position?

I want to set the background color for a specific item in a list.

My listview is generated by an ArrayAdapter using an ArrayList.

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

I know the position of the position in the list.

This is my code to create a list.

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

Thank!

[edit]

According to this post , the use of setSelection is not valid if used in onCreate (), the work around is β€œremove the method onAttachedToWindowin PullToRefreshListView”. I do not quite understand the solution. May I ask how can I do this? I am a subclass Activity, so I can no longer subclass any other class.

+5
source share
2

ArrayAdapter getView (...). View.

: -.

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);
    }
}
+2

.

...

listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {

             if( pos == 1) {
                   // to change the listview background
                   listview.setBackgroundColor(getResources().getColor(R.color.your_color_id));

                   // to change the selected item background color
                   myView.setBackgroundColor(getResources().getColor(R.color.your_color_id));
             }
            }
          });

.

0

All Articles