本文介绍了如何在Android上像按钮一样提供imageview点击效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的 Android 应用程序中有 imageview,我使用它就像一个带有 onClick 事件的按钮,但你可能猜到它在单击时不会给 imageview 一个可点击的效果.我怎样才能做到这一点?
I have imageview in my Android app that I am using like a button with the onClick event given, but as you might guess it is not giving imageview a clickable effect when clicked. How can I achieve that?
推荐答案
可以针对点击/未点击状态设计不同的图片,在onTouchListener中进行如下设置
You can design different images for clicked/not clicked states and set them in the onTouchListener as follows
final ImageView v = (ImageView) findViewById(R.id.button0);
v.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.setImageBitmap(res.getDrawable(R.drawable.img_down));
break;
}
case MotionEvent.ACTION_CANCEL:{
v.setImageBitmap(res.getDrawable(R.drawable.img_up));
break;
}
}
return true;
}
});
更好的选择是你定义一个选择器如下
The better choice is that you define a selector as follows
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:drawable="@drawable/img_down" />
<item android:state_selected="false"
android:drawable="@drawable/img_up" />
</selector>
并选择事件中的图像:
v.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
v.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
return true;
}
});
这篇关于如何在Android上像按钮一样提供imageview点击效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!