0

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

    });
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
maysara
  • 5,873
  • 2
  • 23
  • 34
  • post the error(s) you see in the LogCat. if you find it difficult in the search field copy and paste the package name e.g (com.myapp). it will only show you messages for you app now and easier to see the errors in red lines. – Tasos Oct 29 '15 at 16:05
  • unfortunately , app has stopped – maysara Oct 29 '15 at 16:09
  • go here http://developer.android.com/tools/debugging/debugging-studio.html (and go down to -- View the system log) – Tasos Oct 29 '15 at 16:20

2 Answers2

1

This is not the way you do it. findViewById() search only in the current Activity view, in your code it's R.layout.settings.

Use

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

to start Settings.

In the settings activity add

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

    });

In your main activity add

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

More info: How to manage `startActivityForResult` on Android?

Community
  • 1
  • 1
HellCat2405
  • 752
  • 7
  • 16
0

Try this

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));
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Josef El Bez
  • 302
  • 1
  • 11