20

I need to create a simple Drawable object with needed color as background color, but I don't know how I can do it programmatically without using a XML schema (is it possible really?). Please, tell me, I need it to do for making a LayerDrawable and working with SeekBar (changing background of SeekBar programmatically). Thank you in advance.

3 Answers 3

46

You should try using a ColorDrawable. It can be constructed with a color using the constructor ColorDrawable(int color)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. But please, tell me, how can I set Id for Drawable? I need to set "android:id/background" for a new drawable
I don't understand what you are trying to do. What do you need the id for? You can just add the ColorDrawable to your LayerDrawable using the constructor LayerDrawable(Drawable[] layers). You don't need any id for the ColorDrawable. The id of the layer can then be set with LayerDrawable.setId (int index, int id)
8

As it is suggested by @Thrakbad, you can use ColorDrawable:

    TextView textView = new TextView(this);
    ColorDrawable colorDrawable = new ColorDrawable(0xFFFF0000);
    textView.setBackgroundDrawable(colorDrawable);

Comments

6

ColorDrawable will be helpful you in your case, you can pass parameter color for your drawable.

or you can do something like below:

ImageView imgStatus = (ImageView) findViewById(R.id.imgInfoIcon);
// Load the icon as drawable object
Drawable d = getResources().getDrawable(R.drawable.ic_menu_info_details);

// Get the color of the icon depending on system state
int iconColor = android.graphics.Color.BLACK
if (systemState == Status.ERROR)
    iconColor = android.graphics.Color.RED
else if (systemState == Status.WARNING)
    iconColor = android.graphics.Color.YELLOW
else if (systemState == Status.OK)
    iconColor = android.graphics.Color.GREEN

// Set the correct new color
d.setColorFilter( iconColor, Mode.MULTIPLY );

// Load the updated drawable to the image viewer
imgStatus.setImageDrawable(d);

above code is originally posted here

2 Comments

Thank you. But please, tell me, how can I set Id for Drawable? I need to set "android:id/background" for a new drawable
this way you can't at run time, its better to create function pass your view id, and set appropriate color to your view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.