Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Drawable with needed background color programmatically?

Tags:

android

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.

like image 254
user1841247 Avatar asked Jan 16 '13 12:01

user1841247


3 Answers

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

    TextView textView = new TextView(this);
    ColorDrawable colorDrawable = new ColorDrawable(0xFFFF0000);
    textView.setBackgroundDrawable(colorDrawable);
like image 28
Ayaz Alifov Avatar answered Nov 01 '22 01:11

Ayaz Alifov


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

like image 50
Thrakbad Avatar answered Nov 01 '22 03:11

Thrakbad


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

like image 6
RobinHood Avatar answered Nov 01 '22 02:11

RobinHood