My solution, custom attribute for ImageView :
https://github.com/henrychuangtw/Android-ImageView-hover
Step 1 : declare-styleable
<declare-styleable name="MyImageViewAttr">
<attr name="hover_res" format="reference" />
</declare-styleable>
Step 2 : custom ImageView
public class MyImageView extends ImageView {
int resID, resID_hover;
public MyImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyImageViewAttr);
resID_hover = array.getResourceId(R.styleable.MyImageViewAttr_hover_res, -1);
if(resID_hover != -1){
int[] attrsArray = new int[] {
android.R.attr.src
};
TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
resID = ta.getResourceId(0 , View.NO_ID);
ta.recycle();
setOnTouchListener(listener_onTouch);
}
array.recycle();
}
public MyImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyImageViewAttr);
resID_hover = array.getResourceId(R.styleable.MyImageViewAttr_hover_res, -1);
if(resID_hover != -1){
int[] attrsArray = new int[] {
android.R.attr.src
};
TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
resID = ta.getResourceId(0 , View.NO_ID);
ta.recycle();
setOnTouchListener(listener_onTouch);
}
array.recycle();
}
OnTouchListener listener_onTouch = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setImageResource(resID_hover);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
setImageResource(resID);
break;
default:
break;
}
return false;
}
};
}
Step 3 : declare myattr : xmlns:myattr="http://schemas.android.com/apk/res-auto" in layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myattr="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
Step 4 : set myattr:hover_res for MyImageView
<dev.henrychuang.component.MyImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
myattr:hover_res="@drawable/icon_home_h"
android:src="@drawable/icon_home"/>