gpt4 book ai didi

java - 无法在屏幕旋转时保留菜单项

转载 作者:行者123 更新时间:2023-11-29 23:46:03 25 4
gpt4 key购买 nike

我在 .onCreateOptionsMenu 中创建了一个菜单项 (Spinner),并希望在屏幕旋转时保留选择。我知道使用 SharedPreferences 是常见的做法,但是在这种情况下我有点困惑,因为我没有在 .onCreate() 中创建 View ,而我通常会在其中创建 View 加载我保存的首选项:

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_bar_spinner, menu);
MenuItem item = menu.findItem(R.id.spinner);
mSpinner = (Spinner) item.getActionView();
int selectedPosition = mPrefs.getInt(SPINNER_SELECTION, 0);
mSpinner.setSelection(selectedPosition);
if (isOnline()) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.spiner_list_item_array, R.layout.custom_spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
mPrefsEditor.putInt(SPINNER_SELECTION, i);
mPrefsEditor.commit();
switch (i) {
case 0:
mBaseURL = "https://api.themoviedb.org/3/movie/popular/";
calltoRetrofit(mBaseURL);
break;
case 1:
mBaseURL = "https://api.themoviedb.org/3/movie/top_rated/";
calltoRetrofit(mBaseURL);
break;
case 2:
mIsFavoriteSelected = true;
mMovieURLS.clear();
retrieveMovies();
break;

default:
mBaseURL = "https://api.themoviedb.org/3/movie/popular/";
break;
}


}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});
return true;
} else {
return true;
}
}

编辑:

当我尝试设置 GridLayoutManager 的方向时,我现在收到一个空指针:

 if (savedInstanceState != null){
glm = savedInstanceState.getParcelable(SPINNER_SELECTION);
}
glm.setOrientation(LinearLayoutManager.VERTICAL);

最佳答案

首先,在 onCreate 之外的其他方法中访问 SharedPreferences 是完全有效的。如果您在使用此帖子时遇到问题,请提供错误消息/问题。

其次,为了在屏幕旋转时保留内容,您可以在 Activity 中使用 onSaveInstanceState 来保存微调器选择并在屏幕旋转时在 onCreate 中获取状态.例如:

private int saved_selection = -1

@Override
protected void onCreate(Bundle savedInstanceState) {
//...

if (savedInstanceState != null) {
saved_selection = savedInstanceState.getInt("SPINNER_SELECTION");
}

//...
}

@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("SPINNER_SELECTION", saved_selection);

// call superclass to save any view hierarchy
super.onSaveInstanceState(outState);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
//...
// set `saved_selection = i;` in your adapter
//...
if( saved_selection >= 0 ) {
mSpinner.setSelection(saved_selection);
}
}

关于java - 无法在屏幕旋转时保留菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com