I wanted to know what would be the best way to save the visibility of a button in shared preferences. I have several buttons and I need some to be visible others not depending on what is chosen and when re-entering they remain that way
This is the way I was doing it but it doesn't save
public class MainActivity extends Activity {
Button b1, b2;
TextView tv1;
private static final String boton1_Visible = "boton1_Visible";
private static final String boton2_Visible = "boton2_Visible";
private SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
mSharedPreferences = getPreferences(Context.MODE_PRIVATE);
boton1_Visible.setVisibility((mSharedPreferences.getBoolean(boton1_Visible, true)
? View.INVISIBLE : View.VISIBLE));
boton2_Visible.setVisibility((mSharedPreferences.getBoolean(boton2_Visible, true)
? View.VISIBLE : View.INVISIBLE));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void a(View view){
boton1_Visible.setVisibility(View.INVISIBLE);
boolean visibility1 = boton1_Visible.getVisibility() == View.INVISIBLE;
boton1_Visible.setVisibility(visibility1 ? View.INVISIBLE : View.VISIBLE);
mSharedPreferences.edit().putBoolean(boton1_Visible, visibility1).apply();
boton2_Visible.setVisibility(View.VISIBLE);
boolean visibility2 = boton2_Visible.getVisibility() == View.VISIBLE;
boton2_Visible.setVisibility(visibility2 ? View.VISIBLE : View.INVISIBLE);
mSharedPreferences.edit().putBoolean(boton2_Visible, visibility2).apply();
}
}
I suggest you two methods, to save and get the value.
To save and get the values that correspond to the visibility of the buttons, you would do the following, using the previous methods:
I assume that the method
a()
is a method defined in the layout when clicking the buttons, so:and when starting your Activity you can get the values to assign visibility to the buttons:
You must differentiate which button is the one that is receiving the event to change its visibility and/or change the state of the preferences.
I hope it helps you friend, greetings