一行代码修改所有点击效果

需求

开发过程中,没有说所有的ImageView需要点击效果(点击的时候缩放一下),项目完成提交测试。又说需要效果,很烦。发发牢骚继续实现。

实现

为了做大程度的表现b格。写下如此代码。

@SuppressLint("AppCompatCustomView")
public class ClickImageView extends ImageView implements View.OnClickListener {
    private OnClickListener onclickListener;

    public ClickImageView(Context context) {
        super(context);
        this.setOnClickListener(this);
    }

    public ClickImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.setOnClickListener(this);
    }

    public ClickImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setOnClickListener(this);
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        super.setOnClickListener(this);
        onclickListener = l;
    }

    @Override
    public void onClick(View v) {
        setAnimation(v);
        onclickListener.onClick(v);
    }

    private void setAnimation(View v) {
        v.startAnimation(AnimationUtils.loadAnimation(v.getContext(), R.anim.btn_anim));
    }
}

动画效果自己写,我的动画btn_anim

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
            android:interpolator="@android:anim/accelerate_decelerate_interpolator"
            android:duration="100"
            android:fromXScale="1.0"
            android:fromYScale="1.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toXScale="0.9"
            android:toYScale="0.9"
            android:fillBefore="true"
            android:repeatMode="reverse"></scale>"

</set>

以上代码可完美实现需求效果,只需在项目中把所有需要点击效果的ImageView替换为ClickImageView即可。

延伸

代码实现不重要,主要是表达一种思想,以后项目中的任意多个控件,需要有相同的操作。比如点击动画,触摸动画等,都可以通过这样的方式实现。最终要的是在customeView中,使用装饰者,也即在custome中实现interface,然后留存set的lisetener,在实现中重现设置lisetener事件。在本例中的表现为:onclickListener = l; onclickListener.onClick(v);。

以上,如有不对之处,或有更好的方式,欢迎留言

猜你喜欢

转载自blog.csdn.net/Albert_larry/article/details/81705475