activity backgrounds in android studio

时间:2015-10-29 15:57:57

标签: java android android-background

I have a problem in Android Studio.
I try to change the Activity background from another Activity, but when I run the application, it doesn't work and the application closes

    public class Settings extends Activity
{


     RelativeLayout rl ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);


        RadioButton st2 = (RadioButton)findViewById(R.id.style2);
        final  SeekBar sk = (SeekBar)findViewById(R.id.seekBar);




        st2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


                rl = (RelativeLayout) findViewById(R.id.mainActivity);
                rl.setBackgroundResource(R.drawable.sh4);
            }

    });

2 个答案:

答案 0 :(得分:1)

这不是你这样做的方式。 findViewById()只在当前的活动视图中搜索,在您的代码中搜索R.layout.settings

使用

startActivityForResult(new Intent(MainActivity.this,Settings.class), 1);

开始设置。

在设置活动中添加

st2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Intent intent = new Intent();
                intent.putExtra("background_res", R.drawable.sh4);
                setResult(RESULT_OK, intent);
                finish();
            }

    });

在您的主要活动中添加

 @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data == null) {return;}
    int res = data.getIntExtra("background_res");
    rl = (RelativeLayout) findViewById(R.id.mainActivity);
            rl.setBackgroundResource(res );
  }

更多信息:How to manage `startActivityForResult` on Android?

答案 1 :(得分:0)

试试这个

View nameofyourview = findViewById(R.id.randomViewInMainLayout);
// Find the root view
View root = nameofyourview.getRootView()
// Set the color
root.setBackgroundColor(getResources().getColor(android.R.color.red));