2012-09-27 145 views
11

按照此article我能打造了做出来的图像的切换按钮。我的切换没有任何文字,只是开/关图像。Android的切换按钮

当我的切换按钮创建它的被拉伸并失去它的比例,我怎么让它保留它的原始大小?

这些是图像Im使用:

on http://s14.postimage.org/o4zh0nqzh/toggle_on_9.png

off http://s17.postimage.org/mivfu6mbv/toggle_off_9.png

的代码:

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=""    
/> 

绘制/ 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> 

绘制/ 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> 
+0

请出示一些代码!对于切换按钮 – Shrikant

+0

使用包装的内容已经有... – KMI

+0

WRAP_CONTENT的高度和宽度 – aviran

回答

5

尺寸是 “硬编码”,但他们会与规模的增加你的屏幕。

因此XML可能看起来像:

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

的官方文档的DPS是here

13

尝试以下属性为<ToggleButton>

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

它应该工作。祝你好运:)

+0

这会将图像放在按钮上方,其大小正确,但切换的背景是拉伸的切换图像。我尝试删除android:background =“@ drawable/toggle_bg”,它删除了图像,并将带有切换图像的常规切换按钮带回去。 – aviran

+0

我如何在程序中添加这个属性? android:button =“@ drawable/toggle_bg” – user1737884

+0

你可以使用这些setButtonDrawable(int resid)setButtonDrawable(Drawable d) http://developer.android.com/reference/android/widget/CompoundButton.html#setButtonDrawable( int) –

3

为了支持从姜饼版本到目前的人,我最终使用:

<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"/> 

和绘制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> 

的其他解决方案以上没有为姜饼运作良好,较新的作为任一图标不会在所有显示(与上android:button姜饼)或纵横比丢失(与android:background上JELLY_BEAN_MR1(4.2.2) )。

+0

在上次为我工作的评论“android:button on GINGERBREAD”..谢谢 – CoDe

+0

对我有效,谢谢 – yrazlik