How to change color of ListView items on focus and on click

前端 未结 7 1803
天命终不由人
天命终不由人 2020-11-27 03:44

i have a list View in my app (this is the xml layout):

   


        
7条回答
  •  生来不讨喜
    2020-11-27 04:28

    Declare list item components as final outside your setOnClickListener or whatever you want to apply on your list item like this:

    final View yourView;
    final TextView yourTextView;
    

    And in overriding onClick or whatever method you use, just set colors as needed like this:

    yourView.setBackgroundColor(Color.WHITE/*or whatever RGB suites good contrast*/);
    yourTextView.setTextColor(Color.BLACK/*or whatever RGB suites good contrast*/);
    

    Or without the final declaration, if let's say you implement an onClick() for a custom adapter to populate a list, this is what I used in getView() for my setOnClickListener/onClick():

    //reset color for all list items in case any item was previously selected
    for(int i = 0; i < parent.getChildCount(); i++)
    {
      parent.getChildAt(i).setBackgroundColor(Color.BLACK);
      TextView text=(TextView) parent.getChildAt(i).findViewById(R.id.item);
      text.setTextColor(Color.rgb(0,178,178));
    }
    //highlight currently selected item
     parent.getChildAt(position).setBackgroundColor(Color.rgb(0,178,178));
     TextView text=(TextView) parent.getChildAt(position).findViewById(R.id.item);
     text.setTextColor(Color.rgb(0,178,178));
    

提交回复
热议问题