Change the color of a specified item in a listview for android

↘锁芯ラ 提交于 2019-12-25 04:49:17

问题


I would like to change the text color of only one item in a listview.

This change will be triggered by the result of a running asynctask.

So far I searched on google and all I found was to overwrite the getView() function of the adapter, but this approach is kind of hard since I would need to keep the id of the rows I want to color in a global variable that will be accessed by getView().

Is there another way to simply set the text color of an item from a listview when an event happens ?

EDIT

I create the listview this way:

myListView = (ListView) findViewById(R.id.listView);
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow);
listAdapter.add("test");
myListView.setAdapter(listAdapter);

回答1:


For setting a color for a list item definitely you need to override the getView() method of the Adapter. Here is a small example for updating the color of the list item without using the id of the item.

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simplerow) {
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);
                    if (position % 2 == 0) {  //Place the condition where you want to change the item color.
                        view.setBackgroundColor(Color.GRAY);
                    } else {
                         //Setting to default color.
                        view.setBackgroundColor(Color.WHITE);
                    }
                    return view;
                }
            };

In the above example, all the list item at even number positions will be in GREY color and others will be WHITE color. We cannot do this without implementing the getView(). For reference Click Here




回答2:


You may set custom object vis color in adapter then change color in this adapter and call notifyDataSetChanged()



来源:https://stackoverflow.com/questions/30127473/change-the-color-of-a-specified-item-in-a-listview-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!