How to use selector to tint ImageView?

前端 未结 6 1142
别跟我提以往
别跟我提以往 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:46

    In reference to my solution at https://stackoverflow.com/a/18724834/2136792, there are a few things you're missing:

    TintableImageView.java

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        if (tint != null && tint.isStateful())
            updateTintColor();
    }
    
    public void setColorFilter(ColorStateList tint) {
        this.tint = tint;
        super.setColorFilter(tint.getColorForState(getDrawableState(), 0));
    }
    
    private void updateTintColor() {
        int color = tint.getColorForState(getDrawableState(), 0);
        setColorFilter(color);
    }
    

    drawableStateChanged() must be overridden for the tint to be updated when the element's state changes.

    I'm not sure if referencing a drawable from a drawable might cause an issue, but you can simply move your selector.xml into a folder "/res/color" to reference it with "@color/selector.xml" (aapt merges both /res/values/colors.xml and the /res/color folder).

提交回复
热议问题