Search code examples
androidviewimageviewandroid-view

View.setSelected(bool) is not working when the view is updated programatically in different location


I am running into an issue where the Views I have in the app are not being updated on viewObject.setSelected(true). The View objects contain TextView or ImageView.

myViewObject.setSelected(isSelected);

The issue occurs when I am adding a new feature where the color of the view is changed programmatically using below on specific conditions/events.

TextView myTextView = myViewObject.findViewById(R.id.custom_text_view); 
ImageView myImageView = myViewObject.findViewById(R.id.custom_image_view); 
myTextView.setTextColor(ContextCompat.getColor(mContext, newColor)); 
myImageView.setColorFilter(ContextCompat.getColor(mContext, newColor));

What I am trying to do is keep the original functionality where the View objects' color gets updated when setSelected(bool) is called as above, and also add a new functionality where the Views' colors are changed based on events using setColorFilter.

What I have observed is that the ViewObject.setSelected() works as expected untill I add the code to update color programmatically using setColorFilter(color). After adding code for setColorFilter(color), it works as expected but the setSelected(bool) stops working.

Thanks in advance for your time and advice


Solution

  • This is my understanding. When setColorFilter is used, it sets the color for the image and removes any pre-set tints for the images.

    myImageView.setColorFilter(ContextCompat.getColor(mContext, newColor))
    

    So even though setSelected(bool) is being called, nothing happens

    myViewObject.setSelected(isSelected);
    

    The right method was to use setTint or setTintList using ColorStateList

    Here is an example of creating ColorStateList and then you can set it to the ImageView as below

    myImageView.setImageTintList(myColorStateList);
    

    Note: in the ColorStateList, the negative value is for opposite of the attribute. For example "android.R.attr.state_enabled" indicates selected state and "-android.R.attr.state_enabled" indicates unselected