问题
I am trying to create a stateful Button having Text
and an Image
on the top via the following code:
<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"/>
to get this:
However, I couldn't find the way to change the drawable on the top when the image is pressed.
I tried to set android:drawableTop
to @drawable/multiplayer_stateful
where @drawable/multiplayer_stateful
is :
<?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>
but this doesn't work. (Note that @drawable/multiplayer and @drawable/multiplayer_pressed are png files)
Any suggestions?
回答1:
You have to use android:dither = "true"
Try this.
<?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>
From Android Docs:
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.
Dithering affects how colors that are higher precision than the device are down-sampled. No dithering is generally faster, but higher precision colors are just truncated down (e.g. 8888 -> 565). Dithering tries to distribute the error inherent in this process, to reduce the visual artifacts.
I hope it helps!
回答2:
enable dither attribute in your selector.
android:dither
Boolean. 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). For more detail refer this link:http://developer.android.com/guide/topics/resources/drawable-resource.html
来源:https://stackoverflow.com/questions/32264654/android-button-with-text-with-different-images-for-enabled-and-pressed