开发中经常需要实现可点击的图片、文案、布局,本文是通过对组件的透明度变化实现简单的点击事件,简单而且实用。
以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;
AlphaImageViewhttps://github.com/luninggithub/LnCustomViews/blob/main/library/src/main/java/com/ln/custom/library/widget/alpha/AlphaImageView.javaAlphaRelativeLayouthttps://github.com/luninggithub/LnCustomViews/blob/main/library/src/main/java/com/ln/custom/library/widget/alpha/AlphaRelativeLayout.javaAlphaTextViewhttps://github.com/luninggithub/LnCustomViews/blob/main/library/src/main/java/com/ln/custom/library/widget/alpha/AlphaTextView.java