How to change text color of simple list item

后端 未结 12 2108
清酒与你
清酒与你 2020-11-27 04:12

I have an ListActivity and i am displaying one list with:

setListAdapter(new ArrayAdapter(getApplicationContext(),
                android.R.la         


        
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 04:44

    I realize this question is a bit old but here's a really simple solution that was missing. You don't need to create a custom ListView or even a custom layout.

    Just create an anonymous subclass of ArrayAdapter and override getView(). Let super.getView() handle all the heavy lifting. Since simple_list_item_1 is just a text view you can customize it (e.g. set textColor) and then return it.

    Here's an example from one of my apps. I'm displaying a list of recent locations and I want all occurrences of "Current Location" to be blue and the rest white.

    ListView listView = (ListView) this.findViewById(R.id.listView);
    listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, MobileMuni.getBookmarkStore().getRecentLocations()) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView textView = (TextView) super.getView(position, convertView, parent);
    
            String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
            int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
            textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));
    
            return textView;
        }
    });
    

提交回复
热议问题