2014-11-24 47 views
0

我有一個圖像按鈕:的ImageButton不改變圖像

<ImageButton 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/imageButton" 
    android:layout_weight="0.5" 
    android:layout_column="2" 
    android:background="@null" 
    android:src="@drawable/gender_choice"/> 

的gender_choice.xml如下:

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

出於某種原因,當我運行應用程序,點擊它沒有按按鈕不會改變。是否有必須在點擊監聽器中實現?

+0

因爲'ImageButton'不管理'checked'狀態。你需要一個複選框 – njzk2 2014-11-24 16:54:55

回答

0

嘗試使用您的drawable作爲background而不是src並查看它是否以這種方式工作。

<Button 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/imageButton" 
    android:layout_weight="0.5" 
    android:layout_column="2" 
    android:background="@drawable/gender_choice"/> 

也試着改變你的繪製,並使用state_selectedstate_pressed insteead的state_checked

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@drawable/male_gender" android:state_selected="true" /> 
    <item android:drawable="@drawable/male_gender" android:state_pressed="true" /> 
    <item android:drawable="@drawable/female_gender" /> 
</selector> 
+0

什麼也沒有,它似乎也延伸。沒想到創建一個圖標並使其切換會很困難。 – 2014-11-24 16:45:42

+0

看到我更新的答案!我認爲它會解決你的問題! – 2014-11-24 16:51:31

+0

好像你在正確的軌道上,它會在一秒鐘後返回到相反的性別 – 2014-11-24 17:04:49

0

想通了的傢伙,所以我切換到一個切換按鈕,這裏的大問題是,背景一伸所以對於TableRow來說太大了。爲它放置一個FrameLayout,並解決了所有問題。

所以這裏是我的FrameLayout與ToggleButton,它調用res/drawable文件夾中創建的gender_choice.xml。

<FrameLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_weight="0.5" 
    android:layout_column="2"> 

    <ToggleButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@drawable/gender_choice" 
     android:textOn="" 
     android:textOff="" 
     android:id="@+id/toggleButton" 
     android:layout_gravity="center"/> 
</FrameLayout> 

裏面gender_choice.xml是一個簡單的選擇:

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

這基本上是所有有太多了,我不能相信我花了喜歡上了這4小時。