2011-06-14 54 views
2

我想以編程方式使用選擇器狀態而不是使用xml文件更改ImageView背景(在我的情況下爲漸變顏色)。android以編程方式添加ImageView選擇器

我想壓制和默認狀態,以我的ImageView

有關創建漸變背景我用這個代碼:

GradientDrawable gd = new GradientDrawable(
        GradientDrawable.Orientation.BOTTOM_TOP, 
        new int[] {Color.parseColor(startColour), Color.parseColor(endColour)}); 

如何爲這個工具選擇?

感謝

回答

5

這是從我的應用程序:

public static Drawable getButtonDrawableByScreenCathegory(Context con, 
     ScreenCategory screenCategory, ButtonType buttonType) { 

    int normalStateResID = (int) GXConstants.NOT_ID; 
    int pressedStateResID = R.drawable.button_header_pressed; 

    switch (screenCategory) { 
    ... 
    } 

    Drawable state_normal = con.getResources() 
      .getDrawable(normalStateResID).mutate(); 

    Drawable state_pressed = con.getResources() 
      .getDrawable(pressedStateResID).mutate(); 

    StateListDrawable drawable = new StateListDrawable(); 

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

    return drawable; 
} 

要設置背景,比如說,按鈕,我呼籲:

button.setBackgroundDrawable(GXUtils.getButtonDrawableByScreenCathegory(
      this, mScreenCategory, ButtonType.MENU) 
相關問題