安卓ToggleButton

12

通过遵循这篇article,我成功创建了一个由图像制成的切换按钮。我的切换按钮没有任何文本,只有开/关图像。

当我的切换按钮被创建时,它被拉伸并失去了比例,我该如何使其保持原始大小?

这些是我正在使用的图像:

on

off

代码:

main.xml:

<ToggleButton
   android:id="@+id/changeNumerals"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentLeft="true"
   android:layout_alignParentTop="true"
   android:checked="true"
   android:background="@drawable/toggle_bg"
   android:textOn=""
   android:textOff=""            
/>

drawable/toggle.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_checked="false" android:drawable="@drawable/toggle_off" />
   <item android:state_checked="true" android:drawable="@drawable/toggle_on" />
</selector>

drawable/toggle_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/toggle" />
</layer-list>

使用“wrap content”来设置切换按钮的高度和宽度。 - KMI
wrap_content已经存在... - Aviran
你读过这个吗?http://developer.android.com/guide/practices/screens_support.html - Mr Nice
你正在使用Nine Patch图片吗? - KMI
这些图片是普通的PNG图片,没有9patch黑线。不确定由于它们有圆形部分,这些图片是否可以使用9patch正确地拉伸。 - Aviran
3个回答

13

尝试使用以下属性来使用<ToggleButton>

android:background="@android:color/transparent"
android:button="@drawable/toggle_bg"

应该能够工作。祝好运 :)


这将图像以正确的大小放置在按钮顶部,但切换的背景是拉伸的切换图像。我尝试删除android:background="@drawable/toggle_bg",这将删除图像并恢复常规切换按钮,并在其上方放置我的切换图像。 - Aviran
如何以编程方式添加此属性?android:button="@drawable/toggle_bg" - user1737884
你可以使用这两个方法之一:setButtonDrawable(int resid) 或 setButtonDrawable(Drawable d)。http://developer.android.com/reference/android/widget/CompoundButton.html#setButtonDrawable(int) - Vishal Vyas
谢谢!我的切换按钮与其他图像按钮看起来很奇怪,因为硬编码的大小问题,这个解决方案对我很有帮助! - Casey Murray

7

这些尺寸是“硬编码”的,但它们会随着屏幕大小的变化而缩放。

因此,XML可能如下所示:

android:layout_width="64dp"
android:layout_height="24dp"

dps 的官方文档在 这里


3
为了支持从 GINGERBREAD 版本到当前版本,我最终使用了以下方法:
<ToggleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/filterPhotos"
    android:checked="true"
    android:textOn=""
    android:textOff=""
    android:paddingLeft="5dp"
    android:drawableRight="@drawable/toggle_filter_photos"
    android:background="@null"/>

还有drawable toggle_filter_photos.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/picture_filter_icons"
          android:state_checked="true" />
    <item android:drawable="@drawable/picture_inactive_filter_icons" />
</selector>

对于GINGERBREAD及其更新版本,上述其他解决方案效果不佳,因为使用android:button时图标可能根本不会显示出来,而使用JELLY_BEAN_MR1(4.2.2)上的android:background则可能导致纵横比失真。


请在最后为我添加注释"android:button on GINGERBREAD" ..谢谢 - CoDe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接