简体   繁体   中英

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.

您可以使用setBackgroundResource方法,该方法接受资源ID作为参数。

这段代码正在更改AppCompatButton的颜色

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM