How to use selector to tint ImageView?

前端 未结 6 1139
别跟我提以往
别跟我提以往 2020-11-30 00:58

I want to tint my tabhost\'s icons using XML, instead of doing it programmatically (I wasn\'t able to do that anyway)...

I found this thread on SO: Android imagevie

6条回答
  •  旧巷少年郎
    2020-11-30 01:44

    I implemented this using DrawableCompat from the Android support-v4 library.

    With a regular ImageButton (which subclasses ImageView, so this info also applies to ImageViews), using a black icon from the material icons collection:

    
    

    This is the utility method I created:

    public static void tintButton(@NonNull ImageButton button) {
        ColorStateList colours = button.getResources()
                .getColorStateList(R.color.button_colour);
        Drawable d = DrawableCompat.wrap(button.getDrawable());
        DrawableCompat.setTintList(d, colours);
        button.setImageDrawable(d);
    }
    

    Where res/color/button_colour.xml is a selector that changes the icon colour from red to semi-transparent red when the button is pressed:

    
    
    
        
    
        
    
    
    

    After the ImageButton has been inflated in my activity's onCreate() method, I just call the tintButton(...) helper method once for each button.


    I have tested this on Android 4.1 (my minSdkVersion) and 5.0 devices, but DrawableCompat should work back to Android 1.6.

提交回复
热议问题