Reputation: 6419
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);
}
});
Upvotes: 0
Views: 116
Reputation: 762
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?
Upvotes: 1
Reputation: 212
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));
Upvotes: 0