您需要保存井字游戏板每个框的颜色,并在布局配置更改(即设备旋转)时再次保留它们。
您可能会考虑调查在这里回答以获得您问题的详细解释。您可能会检查开发者文档这里也用于处理配置更改。
关键思想是将布局状态保存在变量中,这些变量在配置更改后仍然存在,并在您的应用程序中相应地更新它们onCreate
or onCreateView
函数的情况下Activity
and Fragment
分别。但是,就您而言,您需要存储大量数据,并且在每次配置更改时,您都需要再次恢复它们,这不是一种有效的方法。我想建议您寻找其他可用的选项,这些选项可以在布局的方向或配置更改后继续存在。
我强烈建议实施ViewModel在您的情况下,它可以在应用程序配置更改后继续存在,并以最有效的方式处理整体 UI 表示。这个想法是将你的 UI 元素与你的ViewModel
然后每次都保留 UI 元素ViewModel
。它可以保留在确切的状态,直到Activity
or Fragment
完成。
对于您的情况,我想提供一个示例,说明如何准备ViewModel
。让我们考虑一下您的ViewModel
is GameModel
它保存了电路板的布局项目。
public class GameModel extends ViewModel {
public final LiveData<Game> gameLiveData = new LiveData<>();
public GameModel() {
// trigger game load.
}
void doAction() {
// depending on the action, do necessary business logic calls and update the gameLiveData.
}
}
public class Game {
public static final int CROSS = 1;
public static final int ZERO = 0;
public int pos1 = -1; // Default values are -1, when the position is yet to be played
public int pos2 = -1;
public int pos3 = -1;
public int pos4 = -1;
public int pos5 = -1;
public int pos6 = -1;
public int pos7 = -1;
public int pos8 = -1;
public int pos9 = -1;
}
现在从你的Activity
,你需要添加一个观察者到你的GameModel
类来相应地更新 UI。
public class UserActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity_layout);
final GameModel viewModel = ViewModelProviders.of(this).get(GameModel.class);
viewModel.gameLiveData.observer(this, new Observer() {
@Override
public void onChanged(@Nullable Game gameData) {
// update ui.
}
});
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Pass parameters in doAction function to set the items in the Game class and update the ui accordingly inside the onChanged function.
viewModel.doAction();
}
});
}
}
希望有帮助!