Home > OS >  Change background color of another activity with button
Change background color of another activity with button

Time:10-07

I have two activities main and settings. I want to change the background color of the main using a button that's on settings. I tried using RelativeLayout and get the layout of the main using the id and changing the color when touching the button but it doesn't work. I also tried doing with Intent but I don't know how to do it. Got the code for the settings activity below

public class Settings extends AppCompatActivity {
    private Button changeColorButton;
    private RelativeLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        changeColorButton = findViewById(R.id.changeColorButton);
        layout = findViewById(R.id.mainLayout);
        /** Called when the user taps the Settings button */
        changeColorButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View V){
                Intent intent = new Intent(Settings.this, Main.class);
                startActivity(intent);
                layout.setBackgroundColor(Color.BLUE);
            }
        });
    }
}

Any help please?

CodePudding user response:

You cannot change views of another activity like that.

You can send an 'extra' parameter with your Intent and read it on Settings activity. You can change the color based on the value you receive via the intent.

Or if its a more permanent setting, you can save it on SharedPreferences and read it on Main.

  • Related