Android 带有不同图像的文本按钮,用于启用和按下

Android Button with Text with different images for Enabled and Pressed

我正在尝试通过以下代码创建一个顶部有 TextImage 的有状态按钮:

<Button
android:id="@+id/btnMultiplayer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableTop="@drawable/multiplayer"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="Multiplayer"/>

得到这个:

但是,我找不到在按下图像时更改顶部可绘制对象的方法。

我试图将 android:drawableTop 设置为 @drawable/multiplayer_stateful 其中 @drawable/multiplayer_stateful 是 :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawableTop="@drawable/multiplayer" android:state_enabled="true" android:state_window_focused="false"/>
<item android:drawableTop="@drawable/multiplayer_pressed" android:state_pressed="true"/>

</selector>

但这不起作用。 (注意@drawable/multiplayer和@drawable/multiplayer_pressed是png文件)

有什么建议吗?

在您的选择器中启用抖动属性。

android:抖动

布尔值。如果位图没有与屏幕相同的像素配置(例如:ARGB 8888 位图与 RGB 565 屏幕),则启用或禁用位图抖动。 有关详细信息,请参阅此 link:http://developer.android.com/guide/topics/resources/drawable-resource.html

你必须使用android:dither = "true"

试试这个。

<?xml version="1.0" encoding="utf-8"?>
<selector 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:dither="true" >

<item android:drawableTop="@drawable/multiplayer" android:state_enabled="true" android:state_window_focused="false"/>
<item android:drawableTop="@drawable/multiplayer_pressed" android:state_pressed="true"/>

</selector>

来自 Android 文档:

Enables or disables dithering of the bitmap if the bitmap does not have the same pixel configuration as the screen (for instance: a ARGB 8888 bitmap with an RGB 565 screen).

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

抖动会影响比设备精度更高的颜色如何被下采样。没有抖动通常更快,但更高精度的颜色只是被截断(例如 8888 -> 565)。抖动尝试分布此过程中固有的错误,以减少视觉伪影。

希望对您有所帮助!