2016-01-22 46 views
2

我有一個RelativeLayout的爲什麼我的RelativeLayout不使用選擇器?

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/container" 
    android:layout_centerInParent="true" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:clickable="true" 
    android:background="@drawable/animated_bg"> 

,我已經定義了一個選擇

<ripple xmlns:android="http://schemas.android.com/apk/res/android" 
android:color="@color/ripple_color"> 
<item> 
    <selector> 
     <item android:state_pressed="true" 
      android:drawable="@color/grey_1" /> 

     <item android:state_focused="true" 
      android:drawable="@color/grey_1" /> 

     <item android:drawable="@color/white" /> 
    </selector> 
</item> 

但是當我按下佈局不改變顏色。

任何人都可以注意到爲什麼會發生這種情況?

更新

下面是完整的XML文件

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/container" 
    android:layout_centerInParent="true" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:clickable="true" 
    android:background="@drawable/animated_bg"> 

    <RelativeLayout> 

     <RelativeLayout> 

      <ImageView /> 

      <LinearLayout> 

       <TextView /> 

       <TextView /> 

      </LinearLayout> 

     </RelativeLayout> 

     <LinearLayout > 

      <LinearLayout > 

       <RelativeLayout > 

        <ImageView /> 

        <TextView /> 

        <TextView /> 

        <TextView /> 

       </RelativeLayout> 

       <RelativeLayout > 

        <ImageView /> 

        <TextView /> 

        <TextView /> 

       </RelativeLayout> 

      </LinearLayout> 

      <LinearLayout > 

       <RelativeLayout > 

        <TextView /> 

       </RelativeLayout> 
      </LinearLayout> 
     </LinearLayout> 

    </RelativeLayout> 

</RelativeLayout> 
+0

似乎一般建議在選擇器中使用構建,除非您想要自定義顏色。強烈建議用'attr/selectableItemBackground'替換'@ drawable/animated_bg'' –

回答

0

在XML選擇顏色爲Android:Android的state_pressed:state_focused是相同的:@色/ grey_1。嘗試給兩種不同的顏色。

<ripple xmlns:android="http://schemas.android.com/apk/res/android" 
android:color="@color/ripple_color"> 
<item> 
    <selector> 
     <item android:state_pressed="true" 
      android:drawable="@color/grey_1" /> 

     <item android:state_focused="true" 
      android:drawable="@color/grey_1" /> 

     <item android:drawable="@color/white" /> 
    </selector> 
</item> 
+0

這不起作用 – Eric

2

我已經用選擇器測試了你的佈局。它運作良好。但是,我不知道您的相對佈局內是否有任何其他視圖/佈局?如果RelativeLayout有子視圖。這些視圖可能會消耗您的事件press,這將導致背景不會更改其顏色。在我的測試中,我的相對佈局中沒有任何子視圖。你能發佈你的整個佈局文件嗎?

更新: 如果您的孩子的意見不需要處理點擊事件,您可以設置android:clickable="false",以便點擊事件將傳遞給您的父親相對佈局。如果情況並非如此,那麼這link可能會幫助你。

+0

我已經添加了完整的佈局結構 – Eric

+0

謝謝。設置子視圖clickable = false和父級clickable = true解決了我的問題! –

相關問題