我正在尝试ToggleButton
在我的应用程序中进行自定义。我正在将 9-patch 图像设置为背景,如此处所写。然后在我的布局xml中:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@drawable/btn_toggle_bg"
android:checked="true"
android:gravity="center_horizontal|center_vertical" />
btn_toogle_bg.xml
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+android:id/background"
android:drawable="@android:color/transparent"/>
<item
android:id="@+android:id/toggle"
android:drawable="@drawable/btn_toggle"/>
</layer-list>
btn_toggle.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_toggle_off" android:state_checked="false"/>
<item android:drawable="@drawable/btn_toggle_on" android:state_checked="true"/>
</selector>
9-patch 看起来像这样(btn_toggle_off
):
检查状态的相同图像。
但是当我将其用作背景时,我会得到一些意想不到的顶部和底部填充:
Button
将此背景应用于或使用 xml-drawable 作为背景时,我得到了相同的结果。如何避免意外填充?请帮忙。
更新:
此外,当我将此样式添加到应用程序主题时,没有填充但变得不可ToggleButton
点击(不改变其状态):
styles.xml
:
<style name="Widget.Button.Toggle" parent="android:Widget">
<item name="android:background">@drawable/btn_toggle_bg</item>
<item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
</style>
themes.xml
:
<style name="MyThemeName" parent="@android:Theme.Black">
<item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
</style>