Android imageview change tint to simulate button click

后端 未结 5 1133
鱼传尺愫
鱼传尺愫 2020-11-30 19:27

I have an imageview on which I have set a bitmap fetched from an url. On the imageview I have set an onClickListener which opens up a dialog.

I want to somehow chang

5条回答
  •  广开言路
    2020-11-30 20:07

    One way would be to use a combination of a ColorFilter and a ColorStateList that contains your tint color for when the button is pressed. The xml for the ColorStateList in the res/color directory would look like this:

    button_pressed.xml

    
    
    
        
        
    
    
    

    where @color/pressed_color is your tint color (which should be partially transparent). Then in your ImageView subclass, you apply the color by overriding drawableStateChanged().

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
    
        ColorStateList list = getResources().getColorStateList(R.color.button_pressed);
        int color = list.getColorForState(getDrawableState(), Color.TRANSPARENT);
        setColorFilter(color);
        invalidate();
    }
    

    Any time the button's state changes, this code is called and will automatically set the tint as appropriate.

提交回复
热议问题