user2277536
user2277536

Reputation: 55

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); 

Upvotes: 0

Views: 7262

Answers (3)

Ashwani kumar
Ashwani kumar

Reputation: 162

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.

Upvotes: 0

rahultheOne
rahultheOne

Reputation: 154

view.setBackgroundResource(R.drawable.example);

Upvotes: 1

Shreyos Adikari
Shreyos Adikari

Reputation: 12744

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

view.setBackgroundColor(Color.RED); 

Upvotes: 2

Related Questions