如何从android sdk中的MainActivity更改activity_main中的背景?
当应用程序运行时,它会创建一个运行changeBackgroundColor的按钮。然后,它会显示一个运行SetBackgrounded的按钮,该按钮会使应用程序崩溃。在如何从android sdk中的MainActivity更改activity_main中的背景?,android,background,Android,Background,当应用程序运行时,它会创建一个运行changeBackgroundColor的按钮。然后,它会显示一个运行SetBackgrounded的按钮,该按钮会使应用程序崩溃。在MainActivity中创建一个类似于 package mine.app; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import androi
MainActivity
中创建一个类似于
package mine.app;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void changeBackgroundColor(View view) {
setContentView(R.layout.color_list);
}
public void setBackgroundRed(View view) {
findViewById(R.layout.activity_main).setBackgroundColor(Color.RED);
setContentView(R.layout.activity_main);
}
}
然后从OnClickListener调用此函数,传入所需颜色。更改onCreate,如下所示
public void setActivityBackgroundColor(int color) {
View view = this.getWindow().getDecorView();
view.setBackgroundColor(color);
}
好的,假设这是您的主要活动,&根据您的“当应用程序运行时,它会创建一个运行changeBackgroundColor的按钮”——您在哪里实例化需要调用(或运行)changeBackgroundColor(View v)方法的按钮?我想您应该在onCreate()中这样做;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setBackgroundDrawableResource(R.color.blue);// specify background drawable resource or background color resource here
}