2011-06-14 112 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)