【发布时间】:2015-11-13 17:26:21
【问题描述】:
我目前正在开发一个使用 Android 的应用程序。我是游戏新手,所以我可以使用一些帮助。我有一个页面充满了带有几个不同图像的 ImageButtons。当他们被按下时,我希望按钮的背景变灰并在用户不再单击按钮时切换回原始图片。
感谢您的帮助!
【问题讨论】:
标签: android image onclick imagebutton
我目前正在开发一个使用 Android 的应用程序。我是游戏新手,所以我可以使用一些帮助。我有一个页面充满了带有几个不同图像的 ImageButtons。当他们被按下时,我希望按钮的背景变灰并在用户不再单击按钮时切换回原始图片。
感谢您的帮助!
【问题讨论】:
标签: android image onclick imagebutton
检查this answer。我认为这与您的问题有关。
对于您的示例,您可以在可绘制文件夹中有一个可绘制对象。随便叫什么。我称它为 button_states.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android:drawable="@drawable/cancel" /> <!-- This can be your image -->
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@color/grey" /> <!-- This can be the color you want to show when the button is pressed. Define this in colors.xml -->
<item
android:state_enabled="true"
android:drawable="@drawable/cancel" /> <!-- Use the same image here -->
</selector>
最后将此可绘制对象添加为 ImageButton 的背景。像这样:
<ImageButton
android:id="@+id/imageButtonSelector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_states" />
【讨论】:
你可以这样做:
final ImageButton imgButton = (ImageButton)view.findViewById(R.id.button);
imageButton.setImageResource(R.drawable.imageIdle);
imgButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
imageButton.setImageResource(R.drawable.imagePressed);
return true;
case MotionEvent.ACTION_UP:
imageButton.setImageResource(R.drawable.imageIdle);
return true;
default:
return false;
}
}
});
希望对你有帮助!
【讨论】: