9补丁背景添加顶部和底部填充。怎么避免呢?

时间:2013-03-24 14:03:35

标签: android nine-patch

我正在尝试在我的应用中自定义ToggleButton。我将9-patch图像设置为背景为here。 然后在我的布局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

检查状态的相同图像。

但是当我将它作为背景应用时,我会得到一些意想不到的顶部和底部填充:

enter image description here enter image description here

将此背景应用于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>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

试试这个:

enter image description here