2012-09-27 64 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