根据用户选择设置listview所选项目背景颜色

时间:2017-10-19 12:30:38

标签: android listview onitemclicklistener

我使用SimpleCursorAdapter来填充带有联系人姓名的ListView。 在listview.onItemClickListener中,我使用以下代码更改视图文本视图的颜色 -

class MyScraper(ABC,scrapy.Spider):
    """Abstract base class for scraping non JS Web pages"""
    #logger = None    # Commented out, as I don't want class instance

    def __init__(self, *args, **kwargs): 
        self.connection = None
        self.channel = None
        self.topic = None            

        log_format = "%(asctime)s - %(levelname)s - %(message)s"
        log_level = 10
        handler = TimedRotatingFileHandler("{0}.log".format(kwargs['log_filename']), when="midnight", interval=1)
        handler.setLevel(log_level)
        formatter = logging.Formatter(log_format)
        handler.setFormatter(formatter)

        # add a suffix which you want
        handler.suffix = "%Y%m%d"

        #need to change the extMatch variable to match the suffix for it
        handler.extMatch = re.compile(r"^\d{8}$") 

        self.logger = logging.getLogger('my_logger') # <- barfs here

        # finally add handler to logger    
        self.logger.addHandler(handler)   

        # Set up messaging infrastructure ...

事情是,当项目的颜色发生变化时,当用户滚动列表时,它也会更改下一页中的项目。

是否有一个我可以覆盖SimpleCursorAdapter的getView方法?

1 个答案:

答案 0 :(得分:0)

        private class ColorTestAdapter extends ArrayAdapter<String> {
            private final Context context;
            private final String[] values;

            public ColorTestAdapter(Context context, String[] values) {
                super(context, R.layout.list_item, values);
                this.context = context;
                this.values = values;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View layout_view = inflater.inflate(R.layout.list_item, parent, false);
                TextView tv = (TextView) layout_view.findViewById(R.id.list_textview);
                // Set text
                tv.setText(values[position]);
                // Set color depending on position
                int textColorId = R.color.black; // Default color
                if(position == 1){
                        textColorId = R.color.red; 
                 }

                }
                tv.setTextColor(getResources().getColor(textColorId));
                return layout_view;
            }
        }

在oncreate中

    myListView = (ListView)findViewById(R.id.main_listView);
        ColorTestAdapter adapter = new ColorTestAdapter(this,myLists);
        myListView.setAdapter(adapter);