Swapnil Sharma Swapnil Sharma - 5 months ago 13
Android Question

How to change background color of first item of a listview after setAdapter is used?

How to change background color of first item or any other item of a listview after setAdapter is used? Basically, I want to change inside onCreate and outside of setOnItemClickListener.

Setting List Array Adapter Code:

ArrayAdapter arrayAdapter = new ArrayAdapter(SecondActivity.this,android.R.layout.simple_list_item_1,strings);

listView.setAdapter(arrayAdapter);

Answer

Try this

you can do that in getView method at your adapter and if you use ArrayAdapter you can also override getView method as following :

     ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,strings){
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {

                    View view;
                    if(convertView==null) {
                        LayoutInflater Inflater = (LayoutInflater) MainActivity.this.getSystemService(MainActivity.this.LAYOUT_INFLATER_SERVICE);
                        view = Inflater.inflate(android.R.layout.simple_list_item_1, null);
                    }
                    else
                    {
                        view=convertView;
                    }
                    if(position==YOUR_TARGET_POSITION_TO_CHANGE_ITS_BACKGROUND)
                    {
                        view.setBackgroundColor(0x2196f3);
                    }
//Update Of textView

                    TextView txt1=(TextView)view.findViewById(android.R.id.text1);
                text1.setText(strings[position]);

    //Rest of your code
                    return view;
                }
            };
    listView.setAdapter(arrayAdapter);