自定义ImageView,点击反馈效果

又是一个简单的自定义ImageView

先上效果图:

点击后不松开的状态是原图加了个阴影。


功能如下:

不点击的时候是某张图片,点击后是某张图片

废话不多讲,上代码:


step1:新建 Java文件 ClickFeedbackImageView.java


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.jabez.demo.R;

/**
 * Created by Jabez on 2017/5/15.
 */

public class ClickFeedbackImageView extends ImageView implements View.OnTouchListener {
    private Drawable mPressedDrawable;
    private Drawable mNormalDrawable;
    public ClickFeedbackImageView(Context context) {
        super(context);
    }

    public ClickFeedbackImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mNormalDrawable = getDrawable();
        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ClickFeedbackImageView);
        /**获取自定义属性pressed的Drawable并用成员变量保存*/
        mPressedDrawable = a.getDrawable(R.styleable.ClickFeedbackImageView_pressed);

        setOnTouchListener(this);

        if (mPressedDrawable !=null && isPressed()) {
            //如果在布局中设置了pressed与normal,我们就要设置ImageView的图片为mPressedDrawable
            setImageDrawable(mPressedDrawable);
        }
        a.recycle();
    }

    @Override
    public void setImageDrawable(@Nullable Drawable drawable) {
        super.setImageDrawable(drawable);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN://按下
                setImageDrawable(mPressedDrawable);
                break;
            case MotionEvent.ACTION_UP://松开
                setImageDrawable(mNormalDrawable);
                break;
            default:break;
        }
        return false;
    }
}


step2:res/value/attr.xml搞事情


-----------如果没有attr.xml就新建一个----------

--------------这里是自定义的属性---------------------------------


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ClickFeedbackImageView">
        <attr name="pressed" format="reference" />
        <attr name="normal" format="reference" />
    </declare-styleable>
</resources>

 
step3:在布局里面用吧

<com.jabez.demo.widget.ClickFeedbackImageView
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:src="@mipmap/img_normal"
    app:pressed="@mipmap/img_pressed"
    android:adjustViewBounds="true"/>
PS:app:pressed="@mipmap/img_pressed"的使用需要在根布局添加这个
xmlns:app="http://schemas.android.com/apk/res-auto"

完工!!!
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值