简体   繁体   中英

How to change background color via java?

Hello I'm a newbie in android development and I am looking forward a way to change the background color.

Here is my code:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// View layout = new View(this);
// layout.setBackgroundColor(android.R.color.holo_blue_light);
// View root = layout.getRootView();
// root.setBackgroundColor(android.R.color.holo_green_dark);
View view = this.getWindow().getDecorView();
view.setBackgroundColor(R.color.red); 

The problem is with the syntax view.setBackgroundColor(R.color.red);
Try:

view.setBackgroundColor(Color.RED); 

view.setBackgroundResource(R.drawable.example);

used this :-

 view.setBackgroundColor(ContextCompat.getColor(context, R.color.color_name))

This will choose the Marshmallow two parameter method or the pre-Marshmallow method appropriately.

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