The Dark Knight
The Dark Knight

Reputation: 5585

How to change color of backGround on app load(onCreate())?

I am trying to change r=the color of the back ground on app load. For this I have used something like this :

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final View view= new View(getApplicationContext());
        view.post(new Runnable() {
            @Override
            public void run() {
                view.setBackgroundColor(Color.BLACK);
            }
        });
        addListenerOnButton();
    }

This does not work. See the emulator screen shot below : enter image description here

As you can see the back ground color is still white . Any ideas on what i can do to rectify this ?

Upvotes: 0

Views: 3346

Answers (3)

priteshbaviskar
priteshbaviskar

Reputation: 2327

This should do the trick:

this.findViewById(android.R.id.content).setBackgroundColor(Color.BLACK);  

Upvotes: 0

Gunaseelan
Gunaseelan

Reputation: 15525

Simple. Try this way.

this.findViewById(android.R.id.content).setBackgroundColor(Color.BLACK);    

For ex:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.findViewById(android.R.id.content).setBackgroundColor(Color.BLACK);
}

Here findViewById(android.R.id.content) will return ContentView of current activity. Then you can set background for this view. I hope this will help you.

Upvotes: 2

SimonSays
SimonSays

Reputation: 10977

First of all, view.post() is not necessary, because onCreate() already runs in the UI thread. Secondly, you are creating a View and setting the background of it, but you never set the view to anywhere, it's just an Object that never gets drawn. There are 2 solutions:

either:

View view= new View(this);
view.setBackgroundColor(Color.BLACK);
setContentView(view);

or, probably better:

setContentView(R.layout.activity_main);
View view = findViewById(R.id.root_laout); // set the root_layout in the layout xml file
view.setBackgroundColor(Color.BLACK);

Upvotes: 0

Related Questions