如何在使用setAdapter后更改listview第一项的背景颜色?

时间:2016-06-16 19:19:02

标签: android listview

如何在使用setAdapter后更改列表视图的第一项或任何其他项的背景颜色?基本上,我想在onCreate内部和setOnItemClickListener之外进行更改。

设置列表数组适配器代码:

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

    listView.setAdapter(arrayAdapter);

1 个答案:

答案 0 :(得分:0)

试试这个

您可以在适配器的getView方法中执行此操作,如果您使用ArrayAdapter,还可以覆盖getView方法,如下所示:

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