What you need is to be able to save the state of the buttons elsewhere. I can name two that you can use: SharedPreferences or ViewModel.
In your case, I suggest creating a ViewModel
class that will hold the state of your buttons.
CustomViewModel class
import androidx.lifecycle.ViewModel;
public class CustomViewModel extends ViewModel {
public boolean button1_gone;
}
Then in your activity:
final CustomViewModel model = new ViewModelProvider(this).get(CustomViewModel.class);
if (model.button1_gone) {
Button butt1 = findViewById(R.id.button1); // I know that butt1 is redundant here
butt1.setVisibility(View.GONE);
Button butt2 = findViewById(R.id.button2);
butt2.setVisibility(View.VISIBLE);
model.button1_gone = true;
}
Button mButton = findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Button butt1 = findViewById(R.id.button1);
butt1.setVisibility(View.GONE);
Button butt2 = findViewById(R.id.button2);
butt2.setVisibility(View.VISIBLE);
model.button1_gone = true;
}
});
Also, don't forget to add these dependencies in your app gradle (The one with app
and not the one with your project's name):
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
Note: You need to add those dependencies or else you won't get the proper constructor for the ViewModelProvider
that takes only one argument.
To know more about ViewModel
, go here: https://developer.android.com/topic/libraries/architecture/viewmodel
IMPORTANT: Don't ever declare UI controllers variables inside your ViewModel
as it will cause memory leaks. UI controllers are TextView
, Button
, etc.