Java中的持久性
如何在Java中使用持久性?如果将Java中的持久性,java,android,persistent,Java,Android,Persistent,如何在Java中使用持久性?如果将item.getItemId()存储在SharedReferences中的onOptionsItemSelected中,然后将开关块移动到一个新函数,以便在onCreate中调用该新函数来恢复选择: public void onCreate(Bundle savedInstanceState) { SharedPreferences prefs = getSharedPreferences("prefName", 0); int thicknes
item.getItemId()
存储在SharedReferences中的onOptionsItemSelected
中,然后将开关
块移动到一个新函数,以便在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
}
}
public void onCreate(Bundle savedInstanceState){
SharedReferences prefs=GetSharedReferences(“prefName”,0);
int thicknessId=prefs.getInt(“thicknessFieldName”,1);//用第一个加载状态替换1
switchScribbleView(厚度ID);
int colorId=prefs.getInt(“colorFieldName”,4);//用第一个加载状态替换4
switchScribbleView(colorId);
//…代码的其余部分
}
公共布尔值onOptionsItemSelected(菜单项项){
int menuId=item.getItemId();
//获取旧值,使其保持不变
SharedReferences prefs=GetSharedReferences(“prefName”,0);
int thicknessId=prefs.getInt(“thicknessFieldName”,0);
int colorId=prefs.getInt(“colorFieldName”,0);
if(menuId=4)//控件颜色
colorId=menuId;
Editor=getSharedReferences(“prefName”,0).edit();
编辑器.putInt(“thicknessFieldName”,thicknessId);
编辑器.putInt(“colorFieldName”,colorId);
commit();
switchScribbleView(item.getItemId();
返回true;
}
私有void开关ScribbleView(int menuId){
开关(menuId){
//…这里是开关组
}
}
您可以使用onSaveInstance()在运行和共享引用之间持久化数据以更永久地持久化数据。共享首选项是达到您要求的持久化级别的方法。您可以发布您尝试使用它们的内容吗?@AlexGittemeier当我的选项是单选按钮时,我可以使应用程序使用共享首选项,但我在任何地方都找不到有关如何使用它们的来源为了能够以我在这里使用的菜单格式工作,有什么帮助吗?作为额外的好处,这个实现将允许您只需再显示3-5行即可显示选定的菜单项。