0

我正在尝试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):

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>
4

2 回答 2

1

看来我需要扩展android:Widget.Button.Toggle样式:

<style name="Widget.Button.Toggle" parent="android:Widget.Button.Toggle">
    <item name="android:background">@drawable/btn_toggle_bg</item>
    <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
</style>
于 2013-03-24T14:23:43.330 回答
0

填充的原因是您的右侧黑色像素描述了内容应该放置的位置,应该是图像从上到下的整个长度。

尝试这个:

在此处输入图像描述

于 2013-03-24T14:13:17.093 回答