【问题标题】:Persistance in Java [closed]Java中的持久性[关闭]
【发布时间】:2013-04-01 23:48:34
【问题描述】:

如何在 Java 中使用持久性?

【问题讨论】:

  • 您可以使用 onSaveInstance() 在运行之间保存数据,并使用 SharedPreferences 更永久地保存数据。
  • 共享首选项是实现您所要求的持久性级别的方法。你能发布你对他们的尝试吗?
  • @AlexGittemeier 当我的选项是单选按钮时,我能够使应用程序以共享偏好工作,但我没有找到任何关于如何能够以我在这里使用的菜单格式工作的资源,有什么帮助吗?

标签: java android persistent


【解决方案1】:

如果您将 item.getItemId() 存储在 SharedPreferences 中的 onOptionsItemSelected 中,然后将 switch 块移动到一个新函数,以便在您的 onCreate 中调用该新函数以恢复选择,该怎么办:

public void onCreate(Bundle savedInstanceState) {
    SharedPreferences prefs = getSharedPreferences("prefName", 0);
    int thicknessId = prefs.getInt("thicknessFieldName", 1); // Replace 1 with first-load state
    switchScribbleView(thicknessId);

    int colorId = prefs.getInt("colorFieldName", 4); // Replace 4 with first-load state
    switchScribbleView(colorId);

    //... rest of code
}

public boolean onOptionsItemSelected(MenuItem item) {
    int menuId = item.getItemId();

    //Get old values so they persist
    SharedPreferences prefs = getSharedPreferences("prefName", 0);
    int thicknessId = prefs.getInt("thicknessFieldName", 0);
    int colorId = prefs.getInt("colorFieldName", 0);

    if (menuId <= 2) // Control Thick and Thin
        thicknessId = menuId;
    else if (menuId >= 4) // Control Color
        colorId = menuId;

    Editor editor = getSharedPreferences("prefName", 0).edit();
    editor.putInt("thicknessFieldName", thicknessId);
    editor.putInt("colorFieldName", colorId);
    editor.commit();

    switchScribbleView(item.getItemId();
    return true;
}

private void switchScribbleView(int menuId) {
    switch (menuId) {
        //... switch block here
    }
}

【讨论】:

  • 作为一个额外的好处,这个实现将允许您只多显示 3-5 行选定的菜单项。
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 2012-12-26
  • 2011-06-08
  • 2012-08-09
  • 1970-01-01
相关资源
最近更新 更多