2

I want to change ImageView background (in my case gradient color) using selector state programmatically not by using xml file.

I want pressed and default state to my ImageView

For creating gradient background I use this code:

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

How can I implement selector for this?

Thanks

Jovan
  • 4,684
  • 13
  • 64
  • 98

1 Answers1

6

this is from my app:

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;
}

To setup background for, say, button I call:

button.setBackgroundDrawable(GXUtils.getButtonDrawableByScreenCathegory(
            this, mScreenCategory, ButtonType.MENU)
woodshy
  • 4,085
  • 3
  • 22
  • 21