【发布时间】:2016-11-27 10:12:57
【问题描述】:
我在 Android 中有一个
ImageButton,并且需要在按下按钮时更改图像,以便用户清楚地知道按钮正在被按下。
我尝试的是在我的图像所在的可绘制文件夹中使用带有选择器的 xml。我的代码如下:
xml
<ImageButton
android:id="@+id/upButton"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="@drawable/up_button"
android:background="#00000000"/>
up_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/up_pressed"
android:state_pressed="true"/>
<item android:drawable="@drawable/up"/>
</selector>
java onTouchListener
textView 的文本在按下按钮时更改,并在释放按钮时更改回来。
upButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()){
case MotionEvent.ACTION_DOWN:
textView.setText("Up button pressed.");
break;
case MotionEvent.ACTION_UP:
textView.setText("Up button released.");
break;
}
return true;
}
});
在此站点上搜索类似问题时,我找到了Android button on pressed,但这并没有太大帮助,因为它没有答案。我还发现了很多其他类似的问题并尝试了这些答案,但都没有奏效。我从 Android 文档中的内容开始,在处理其他问题时尝试了它的变体。 https://developer.android.com/guide/topics/ui/controls/button.html
【问题讨论】:
-
尝试设置
android:background="@drawable/up_button"并完全删除src。 -
@Vucko 谢谢。刚刚尝试过,但它不起作用。此外,图像会垂直拉伸。由于
wrap_content,它围绕图像的(垂直)大小延伸,这比我希望它在按钮上的大小要大。 -
@Vucko 我在
styles.xml中为我的imageButton 制作了一个样式,并在Gramowski 的回答中创建了一个themes.xml。我将<item name="android:buttonStyle">更改为<item name="android:imageButtonStyle">,因为我正在使用ImageButton。这没有用......另外,我不确定这是否是正确的解决方案,如果它有效,考虑到这会生成一个ImageButton并在这样的情况下更改所有这些,因为它会覆盖默认值。我需要更多不同的 ImageButton(一个用于向上,一个用于向下),但你不可能知道这一点。很抱歉那里缺乏细节。