2013-04-07 66 views
1

我試圖通過選擇器更改我的按鈕的顏色,當在XML佈局文件中程序員指定該按鈕不可點擊時。即。 android:clickable="false"這是我當前的選擇器XML文件,它似乎不能正常工作。可點擊時更改Button的背景顏色爲false

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" > 
     <item android:state_enabled="false"> 
     <shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
      <solid android:color="#FF00FF"/> 
      <corners 
      android:bottomRightRadius="16dp" 
      android:bottomLeftRadius="16dp" 
      android:topRightRadius="16dp" 
      android:topLeftRadius="16dp"/> 
     </shape> 
    </item> 

<item android:state_pressed="true"> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
     <solid android:color="#CDAF95"/> 
     <corners 
     android:bottomRightRadius="16dp" 
     android:bottomLeftRadius="16dp" 
     android:topRightRadius="16dp" 
     android:topLeftRadius="16dp"/> 
    </shape> 
</item> 

<item> 
    <shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <solid android:color="#D2B48C"/> 
    <corners 
    android:bottomRightRadius="16dp" 
    android:bottomLeftRadius="16dp" 
    android:topRightRadius="16dp" 
    android:topLeftRadius="16dp"/> 

+0

刪除形狀標記的名稱空間屬性......即刪除這個'xmlns:android =「http://schemas.android.com/apk/res/android」' – Pragnani 2013-04-07 13:39:38

回答

2

不幸的是,有一個爲StateListDrawable沒有state_clickable屬性。您可以通過兩種方式解決問題:

  1. 更改視圖的背景,當調用setClickable()時。
  2. 介紹您自己的state_clickable選擇器狀態。

如果你喜歡第二種方式,則需要以下更改添加到項目:

attrs.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="ClickableState"> 
     <attr name="state_clickable" format="boolean" /> 
    </declare-styleable> 
</resources> 

MyButton.java

private static final int[] STATE_CLICKABLE = {R.attr.state_clickable}; 

@Override 
protected int[] onCreateDrawableState(final int extraSpace) { 
    if (isClickable()) { 
     final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); 
     mergeDrawableStates(drawableState, STATE_CLICKABLE); 
     return drawableState; 
    } else { 
     return super.onCreateDrawableState(extraSpace); 
    } 
} 

@Override 
public void setClickable(final boolean clickable) { 
    super.setClickable(clickable); 
    refreshDrawableState(); 
} 

backgrou nd.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:auto="http://schemas.android.com/apk/res-auto"> 
    <item auto:state_clickable="false"> 
     <!-- non-clickable shape here --> 
    </item> 

    <!-- other shapes --> 
</selector> 

但這種方法有一個非常顯著的弱點。如果您想在不同的視圖類中使用此狀態,則必須對這些類進行子類化並將MyButton.java中的代碼添加到它們中。

+0

你怎麼知道setClickable被調用了? – Matthew 2013-04-07 14:55:46

+0

你的意思是第二種解決方案?你重寫'setClickable()'方法,這就是你現在的樣子。 – Michael 2013-04-07 15:08:24