Вы сохраните свои состояния кнопок, используя способ по умолчанию, который реализует onSaveInstanceState()
.
Вы создадите класс, который будет сохранять состояние ваших кнопок .Этот класс будет реализовывать Parcelable,
, чтобы передать его как ArrayList<Parcelable>
параметру Bundle
в onSaveInstanceState()
.
Вот источник этого ответа .
Редактировать:
Я полагаю, что это основная идея реализации, она проста, но я что-то упускаю в создании кнопок, и кнопки странно создаются после поворота.Под странным я подразумеваю, что фон не был по умолчанию, и шрифт больше, чем он не должен быть, потому что я устанавливаю тот же размер (верно, я?).
Чтобы доказать, что какое-то состояние сохраняетсяэто можно увидеть по тексту кнопки, а также по цвету фона, если нажать кнопку.
Основная деятельность:
public class MainActivity extends AppCompatActivity {
private static final String EXTRA_BUTTONS = "extra button list";
private static final int BUTTONS_COUNT = 5;
private ArrayList<Button> createdButtons = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout root = findViewById(R.id.root);
if (savedInstanceState == null) {
createButtonsForTheFirstTime(root);
} else {
createButtonsFromState(savedInstanceState, root);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ArrayList<ButtonViewState> states = new ArrayList<>();
for (int i = 0; i < BUTTONS_COUNT; i++) {
states.add(ButtonViewState.create(createdButtons.get(i)));
}
outState.putParcelableArrayList(EXTRA_BUTTONS, states);
}
private void createButtonsForTheFirstTime(LinearLayout root) {
for (int i = 0; i < BUTTONS_COUNT; i++) {
Button button = createButton(i);
// Save the button so we can retrieve them when we want to save their state
createdButtons.add(button);
// I added the listener which changes the color onClick to prove that state remains
button.setOnClickListener((view) -> view.setBackgroundColor(Color.GREEN));
root.addView(button);
}
}
private void createButtonsFromState(Bundle savedInstanceState, LinearLayout root) {
ArrayList<ButtonViewState> states = savedInstanceState.getParcelableArrayList(EXTRA_BUTTONS);
for (ButtonViewState state : states) {
Button button = createButtonFrom(state);
button.setOnClickListener((view) -> view.setBackgroundColor(Color.GREEN));
root.addView(button);
createdButtons.add(button);
}
}
@NonNull
private Button createButton(int id) {
Button button = new Button(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setText("Button " + id);
button.setId(id);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
return button;
}
private Button createButtonFrom(ButtonViewState state) {
Button button = new Button(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP,state.textSize);
button.setText(state.text);
button.setBackgroundColor(state.backgroundColor);
return button;
}
static class ButtonViewState implements Parcelable {
String text;
int width, height, id;
float textSize;
int backgroundColor;
private ButtonViewState(Button button) {
text = button.getText().toString();
width = button.getLayoutParams().width;
height = button.getLayoutParams().height;
textSize = button.getTextSize();
id = button.getId();
initializeBackgroundColor(button);
}
protected ButtonViewState(Parcel in) {
text = in.readString();
width = in.readInt();
height = in.readInt();
id = in.readInt();
textSize = in.readFloat();
backgroundColor = in.readInt();
}
public static final Creator<ButtonViewState> CREATOR = new Creator<ButtonViewState>() {
@Override
public ButtonViewState createFromParcel(Parcel in) {
return new ButtonViewState(in);
}
@Override
public ButtonViewState[] newArray(int size) {
return new ButtonViewState[size];
}
};
private void initializeBackgroundColor(Button button) {
try {
ColorDrawable drawable = (ColorDrawable) button.getBackground();
backgroundColor = drawable.getColor();
} catch (ClassCastException e) {
Log.e("MainActivity", "Background of button is not a color");
}
}
static ButtonViewState create(Button button) {
return new ButtonViewState(button);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(text);
parcel.writeInt(width);
parcel.writeInt(height);
parcel.writeInt(id);
parcel.writeFloat(textSize);
parcel.writeInt(backgroundColor);
}
}
}
макет:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="32sp" />
</LinearLayout>
Странная часть:
Когда деятельность впервые создается

Нажмите кнопку

После поворота (некоторое состояние сохранено, текст, цвет, здесь кто-то может помочь)
