2014-04-19 45 views
0

不切换我的Android应用程序,我试图让两个图像之间的简单切换按钮切换,实际上是一个明星标记为收藏。按钮的状态正在改变,但图像不能在ON和OFF状态下切换。持续显示OFF状态的图像。形象的Android定制切换按钮

我曾尝试以下教程: http://www.coderzheaven.com/2012/05/20/create-custom-toggle-button-android/ http://www.technotalkative.com/android-custom-toggle-button-example/

** ** togbtn_fav_custom.xml

<item android:drawable="@drawable/ic_action_important" android:state_checked="true" android:state_pressed="true"/> 
<item android:drawable="@drawable/ic_action_important" android:state_checked="true" android:state_focused="false"/> 
<item android:drawable="@drawable/ic_action_not_important" android:state_checked="false" android:state_pressed="true"/> 
<item android:drawable="@drawable/ic_action_not_important" android:state_checked="false" android:state_focused="false"/> 

layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 

    > 
    <android.support.v4.view.ViewPager 
     android:id="@+id/pager" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" /> 

    <LinearLayout 
     android:id="@+id/ll_back_single_dua_footer" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 

     android:gravity="center_vertical" > 

     <Button 
      android:id="@+id/btn_play_pause_dua" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_margin="5dp" 
      android:background="@drawable/play_btn_custom" /> 


     <TextView 
      android:id="@+id/tv_back_single_dua_footer_counter" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:gravity="center_horizontal" 
      android:singleLine="true" 
      android:text="@string/sample_counter" 

      android:textSize="23sp" /> 

     <ToggleButton 
      android:id="@+id/tog_btn_favorite_dua" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
     android:background="@drawable/togbtn_fav_custom" 
     android:textOff="" 
     android:textOn="" 
     /> 
    </LinearLayout> 

    </LinearLayout> 

任何人都可以请指导我我错过了什么?

+0

你的xml文件名是selector.xml还是togbtn_fav_custom.xml? – Riser

+0

togbtn_fav_custom.xml – user2011302

+0

正确检查您的文件。 – Riser

回答

0

尽量简化你这样的selector.xml:

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

而且跟腱说,查线

android:background="@drawable/togbtn_fav_custom" 

可能是你需要设置selector.xml作为背景?

+0

我在另一个活动中尝试了相同的代码,它工作正常。我在Fragment中使用上述代码时发生问题。你能解释一下,为什么? – user2011302