简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM