我有一个笔记应用程序,我实现了两种类型的视图:列表和网格视图。
用户可以根据自己的选择在listView
和gridView
之间切换。我遇到的问题是我一直在尝试持久保存视图状态,以便在启动时打开所选视图。我试图使用SharedPreferences
来实现这一目标。我的代码中出了什么问题?
private static final String KEY_NAME = "viewState";
private ListView mListNotes;
private GridView mGridNotes;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
private boolean mViewIsChanged = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the layouts for list/grid
mListNotes = (ListView) findViewById(R.id.main_listview);
mGridNotes = (GridView) findViewById(R.id.main_gridview);
// Retrieve value from Shared Preferences.
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
mViewIsChanged = sharedPreferences.getBoolean(KEY_NAME, false);
if (!mViewIsChanged){
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);}
else {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customTitleView = inflater.inflate(R.layout.dialog_menu, null);
LinearLayout mListViewSelect = (LinearLayout) customTitleView.findViewById(R.id.list_select);
LinearLayout mGridViewSelect = (LinearLayout) customTitleView.findViewById(R.id.grid_select);
switch (item.getItemId()) {
case R.id.addItem:
// start NoteActivity
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.changeView:
final AlertDialog alertbox = new AlertDialog.Builder(this).create();
alertbox.setCancelable(true);
alertbox.setView(customTitleView);
alertbox.show();
mListViewSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Saving Data
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(KEY_NAME, mViewIsChanged);
editor.apply();
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);
alertbox.dismiss();
}
});
mGridViewSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// saving Data in SharedPreferences
mViewIsChanged = true;
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(KEY_NAME, mViewIsChanged);
editor.apply();
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
alertbox.dismiss();
}
});
答案 0 :(得分:1)
在你的onCreate()之后
mViewIsChanged = sharedPreferences.getBoolean(KEY_NAME, false);
mListNotes = (ListView) findViewById(R.id.main_listview);
mGridNotes = (GridView) findViewById(R.id.main_gridview);
添加此
If (!mViewIsChanged){
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);}
else {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
}
或者在你的onResume()中设置适配器之后输入我提供的逻辑 希望有所帮助。