Skip to content Skip to sidebar Skip to footer

Click Button And Change Background Color Of Another Button

I am making an app in Android Studio. On one of my activities, there are a bunch of buttons, and when you click one, a PopupWindow class appears which has 4 different coloured butt

Solution 1:

If I understand your goal correctly, one possible way to accomplish this is by using SharedPreferences and Extras.

A Shared Preferences file is a file stored in the device's file system locally. It allows you to store information as key-value pairs, and the information remains there even when you exit your application. It is mainly used for storing your application-specific settings. This way, you can permanently save the colors for each button selected by the user.

Extras are for transporting information between Activites when you start an Activity from another using an Intent.

You need to add this to your MainActivity's onCreate():

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferencessharedPref= getSharedPreferences(
                "MY_PREFS", Context.MODE_PRIVATE);

        ...
}

Code for button initializing and handling press (e.g button2):

//-1 is a default value in case no color was selected yet for the particular buttonintbutton2Color= sharedPref.getInt("button2Color", -1);
Buttonbutton2= (Button) findViewById(R.id.button2);
if (button2Color != -1) {
      button2.setBackgroundColor(button2Color);
}
button2.setOnClickListener(newView.OnClickListener() {
     @OverridepublicvoidonClick(View v) {
           Intenti=newIntent(LambertsLaneSection1Activity.this, Pop.class);
           //2 here identifies your button, because it is button2
           i.putExtra("buttonPressed",2)
           startActivity(i);
     }
});

In your PopUp:

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.popupwindow);

    //here you get which button was pressed as an ExtraintbuttonPressed= getIntent().getExtras().getInt("buttonPressed");
    SharedPreferencessharedPref= getSharedPreferences(
                "MY_PREFS", Context.MODE_PRIVATE);
    ...

    finalButtoncolor1Button= (Button) findViewById(R.id.redbutton);
    color1Button.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {
             sharedPref.edit().putInt("button"+buttonPressed+"Color", Color.RED).apply();
        }
    }
}

Post a Comment for "Click Button And Change Background Color Of Another Button"