自带点击效果的ImageView、TextView、RelativeLayout

开发中经常需要实现可点击的图片、文案、布局,本文是通过对组件的透明度变化实现简单的点击事件,简单而且实用。
以ImageView为例(TextView和RelativeLayout类似)直接上代码:

/**
 * 可点击的ImageView,具有点击态效果
 *
 * @author luninggithub
 */
public class AlphaImageView extends AppCompatImageView {

    private ObjectAnimator mAnimatorOut;

    private boolean mIsClick = false;

    public AlphaImageView(Context context) {
        super(context);
        init();
    }

    public AlphaImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AlphaImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() { // 1. 初始化animator
        mAnimatorOut = ObjectAnimator.ofFloat(this, "alpha", 0.4f, 1f);
        mAnimatorOut.setDuration(100);
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        mIsClick = l != null;
        super.setOnClickListener(l);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) { // 2. 重写Touch事件
        if (mIsClick && isEnabled()) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    this.setAlpha(0.4f);
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    mAnimatorOut.start();
                    break;
            }
        }
        return super.onTouchEvent(event);
    }

}

声明Animator对象mAnimatorOut且初始化时设置透明度渐变范围0.4f~1.0f,渐变周期为100ms

mAnimatorOut = ObjectAnimator.ofFloat(this, "alpha", 0.4f, 1f);
mAnimatorOut.setDuration(100);

重写onTouchEvent事件,判断当前是否设置了listener且可点击。DOWN事件时设置初始透明度0.4f,UP和CANCEL事件时Animator start

switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
             this.setAlpha(0.4f);
             break;
      case MotionEvent.ACTION_UP:
      case MotionEvent.ACTION_CANCEL:
             mAnimatorOut.start();
             break;

AlphaImageViewicon-default.png?t=M0H8https://github.com/luninggithub/LnCustomViews/blob/main/library/src/main/java/com/ln/custom/library/widget/alpha/AlphaImageView.javaAlphaRelativeLayouticon-default.png?t=M0H8https://github.com/luninggithub/LnCustomViews/blob/main/library/src/main/java/com/ln/custom/library/widget/alpha/AlphaRelativeLayout.javaAlphaTextViewicon-default.png?t=M0H8https://github.com/luninggithub/LnCustomViews/blob/main/library/src/main/java/com/ln/custom/library/widget/alpha/AlphaTextView.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值