2014-11-24 92 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小时。