2012-10-05 26 views
3

我試圖編程設置一個StateListDrawable作爲我的自定義視圖的庫項目的背景。下面是我在做什麼:StateListDrawable不工作

final TypedArray a = getContext().obtainStyledAttributes(attrs, 
      R.styleable.ActionBar); 
    int firstColor = a.getColor(
      R.styleable.ActionBar_backgroundGradientFirstColor, 0xff000000); 
    int secondColor = a 
      .getColor(R.styleable.ActionBar_backgroundGradientSecondColor, 
        0xff000000); 
    int textViewColor = a.getColor(R.styleable.ActionBar_titleColor, 
      0xffffffff); 
    int onClickColor = a.getColor(
      R.styleable.ActionBar_backgroundClickedColor, 0xff999999); 
    a.recycle(); 

    StateListDrawable sld = new StateListDrawable(); 
    GradientDrawable drawable = new GradientDrawable(
      Orientation.TOP_BOTTOM, new int[] { firstColor, secondColor }); 
    sld.addState(new int[] { android.R.attr.state_enabled }, 
      new ColorDrawable(onClickColor)); 
    sld.addState(new int[] { android.R.attr.state_pressed }, drawable); 

    action2.setBackgroundDrawable(sld); 
    action3.setBackgroundDrawable(sld); 
    actionBack.setBackgroundDrawable(sld); 
    pb.setBackgroundDrawable(drawable); 
    tv.setBackgroundDrawable(drawable); 
    tv.setTextColor(textViewColor); 

但是,這是行不通的:它總是得出啓用狀態。我想讓它畫出按下的狀態,當我按下的按鈕。我究竟做錯了什麼?

+0

以防萬一:使用XML是不是一種選擇,因爲我想這是儘可能定製(它是一個UI庫,所以我希望用戶能夠通過他們的XML定製它) – razielsarafan

回答

20

我猜這個按鈕在按下時仍然是可用的嗎?

你可以嘗試反向排序:

sld.addState(new int[] { android.R.attr.state_pressed }, drawable); 
sld.addState(new int[] { android.R.attr.state_enabled }, 
     new ColorDrawable(onClickColor)); 

可能是第一個當前有效的狀態正在繪製。

如果你想有一個不同的背景當的按下,另一個背景的所有其他情況下,你還可以用它:

sld.addState(new int[] { android.R.attr.state_pressed }, drawable); 
sld.addState(new int[] { StateSet.WILD_CARD }, 
     new ColorDrawable(onClickColor)); 

增加:我只是測試這一點,下面的測試代碼對我的作品:

Button testButton = new Button(context); 
      testButton.setText("Test"); 
      StateListDrawable sld = new StateListDrawable(); 
      GradientDrawable drawable = new GradientDrawable(
        Orientation.TOP_BOTTOM, new int[] { Color.BLUE, Color.RED }); 
      sld.addState(new int[] { android.R.attr.state_pressed }, drawable); 
      sld.addState(StateSet.WILD_CARD, new ColorDrawable(Color.YELLOW)); 
      testButton.setBackgroundDrawable(sld);   
      mainLayout.addView(testButton); 
+0

兩個這樣做的方式使我的按鈕始終具有state_enabled或WILD_CARD狀態,即使我按它。 – razielsarafan

+0

我justed測試了這個自己,它絕對適合我。如果您使用自定義按鈕視圖,也許您應該調查是否由於某種原因從未進入按下狀態?另外請注意,只有當您用手指按下按鈕時纔會出現可壓縮圖案。從按鈕釋放手指的那一刻,該按鈕不再按下,因此默認背景將再次繪製。 – Hendrik

+0

好吧,我設法讓它工作。但是,只要我觸摸按鈕,就會按下整個父級佈局。我使用與該佈局中所有視圖子項相同的sld作爲該問題? – razielsarafan