[英]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
. 我正在使用Android Studio,并且想使用colors.xml文件更改按钮
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.
我想更好的方法意味着更快,消耗更少的内存/ cpu使用率。
您可以使用setBackgroundResource
方法,该方法接受资源ID作为参数。
这段代码正在更改AppCompatButton的颜色
button.getBackground().setColorFilter(ContextCompat.getColor(this, android.R.color.holo_orange_light), PorterDuff.Mode.MULTIPLY);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.