自定義ImageView,點選反饋效果
阿新 • • 發佈:2019-02-05
又是一個簡單的自定義ImageView
先上效果圖:
點選後不鬆開的狀態是原圖加了個陰影。功能如下:
不點選的時候是某張圖片,點選後是某張圖片
廢話不多講,上程式碼:
step1:新建 Java檔案 ClickFeedbackImageView.java
import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; importandroid.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.ClickFeedbackImageViewandroid: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"
完工!!!