I have an activity where the user can choose how many button should be created. If the user types 5 in an EditText that is in an AlertDialog Builder, 5 buttons are created programmatically. If I go back, the created Buttons are gone. How can I save the 5 buttons in the Activity?
This is my code that creates Buttons dynamically:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("How many Buttons?");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String persons = input.getText().toString();
try {
personsnumber = Integer.parseInt(persons);
} catch (NumberFormatException nfe) {}
Button[] buttons = new Button[personsnumber];
for (int l = 0; l < personsnumber; l++) {
buttons[l] = new Button(HandleTableClick.this);
buttons[l].setTextSize(20);
buttons[l].setLayoutParams(lp);
buttons[l].setId(l);
buttons[l].setText("Person" + (l + 1) + "bblabla");
// myLayout.addView(pairs[l]);
myLayout.addView(buttons[l]);
}
}
});
alert.show();
I know that I have to override the OnBackPress
Method but I don't know what code I should use to save the state.
You will save your buttons states using the default way which is implementing
onSaveInstanceState()
.You will create a class that will save the state of your buttons. That class would implement
Parcelable,
in order to pass it as anArrayList<Parcelable>
to theBundle
parameter inonSaveInstanceState()
.Here is the source of this answer.
Edit:
I believe this is the main idea behind the implementation, it's simple, yet I am missing something about the button creation and the buttons are weirdly created after rotating. By weirdly I mean that the background was not the default and the font is larger which it should not be because I am setting the same size (am I, right?).
To prove that some state is kept you can see it from the text of the button and also from the background color if you press the button.
The main activity:
The layout:
The weird part:
When activity is first created
Click a button
After rotatation (some state is preserve, text, color, someone could help here)