Tint / dim drawable on touch

前端 未结 8 1473
别跟我提以往
别跟我提以往 2021-01-31 11:24

The app I\'m currently working on uses a lot of ImageViews as buttons. The graphics on these buttons use the alpha channel to fade out the edges of the button and make them look

8条回答
  •  遥遥无期
    2021-01-31 11:40

    For those who have encountered a similar need, solving this in code is fairly clean. Here is a sample:

    public class TintableButton extends ImageView {
    
        private boolean mIsSelected;
    
        public TintableButton(Context context) {
            super(context);
            init();
        }   
    
        public TintableButton(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }   
    
        public TintableButton(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        private void init() {
            mIsSelected = false;
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN && !mIsSelected) {
                setColorFilter(0x99000000);
                mIsSelected = true;
            } else if (event.getAction() == MotionEvent.ACTION_UP && mIsSelected) {
                setColorFilter(Color.TRANSPARENT);
                mIsSelected = false;
            }
    
            return super.onTouchEvent(event);
        }
    }
    

    It's not finished but works well as a proof of concept.

提交回复
热议问题