如何在app load(onCreate())上更改backGround的颜色?

时间:2013-05-22 16:43:49

标签: android

我正在尝试更改应用程序加载时r =背景颜色。为此,我使用了这样的东西:

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

这不起作用。请参阅下面的模拟器屏幕截图: enter image description here

正如您所看到的,背景颜色仍然是白色。关于我能做些什么来纠正这个问题的任何想法?

3 个答案:

答案 0 :(得分:2)

简单。试试这种方式。

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

例如:

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

此处findViewById(android.R.id.content)将返回当前活动的ContentView。然后,您可以为此视图设置背景。 我希望这会对你有所帮助。

答案 1 :(得分:0)

首先,view.post()不是必需的,因为onCreate()已经在UI线程中运行。其次,您正在创建一个视图并设置它的背景,但您从未将视图设置为任何位置,它只是一个永远不会被绘制的对象。有两种解决方案:

或者:

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

或者,可能更好:

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

答案 2 :(得分:0)

这应该可以解决问题:

this.findViewById(android.R.id.content).setBackgroundColor(Color.BLACK);  
相关问题