twharmon
twharmon

Reputation: 4272

How to programmatically change the background color of a button

I am using Android Studio and would like to use the colors.xml file to change the background color of a button btn. Both of these work for me:

btn.setBackgroundColor(getResources().getColor(R.color.colorBlue, null));

and

btn.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorBlue));

Which one is better? I guess better means faster and consuming less memory/cpu usage.

Upvotes: 0

Views: 6954

Answers (2)

AndrewS
AndrewS

Reputation: 7508

This code is changing color of AppCompatButton

button.getBackground().setColorFilter(ContextCompat.getColor(this, android.R.color.holo_orange_light), PorterDuff.Mode.MULTIPLY);

Upvotes: 3

Redan Hassoun
Redan Hassoun

Reputation: 106

You can use the setBackgroundResource method which accepts the resource id as a parameter.

Upvotes: 4

Related Questions