我想从微调器中存储选定的项目,一旦该片段再次启动,应该选择之前选择的项目,我尝试但无法获得它。
我只需要在按钮上存储选定的位置。
这是我正在使用的代码:
spinner_level = (Spinner)rootView.findViewById(R.id.spinner_activity_level);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(rootView.getContext(), R.array.activity_level, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner_level.setAdapter(adapter);
spinner_level.setGravity(Gravity.CENTER);
spinner_level.getSelectedItemPosition();
spinner_level.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
((TextView) parentView.getChildAt(0)).setTextColor(Color.BLACK);
selected = parentView.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
答案 0 :(得分:0)
每次在此代码已存在的Framgent onCreateView
中初始化微调器时,您需要设置所选值:
spinner_level = (Spinner)rootView.findViewById(R.id.spinner_activity_level);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(rootView.getContext(), R.array.activity_level, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner_level.setAdapter(adapter);
spinner_level.setGravity(Gravity.CENTER);
spinner_level.getSelectedItemPosition();
int indexOfPreviousSelection = sharedPreferences.getInt("selectionIndex", 0);
spinner_level.setSelection(indexOfPreviousSelection);
您需要从indexOfPreviousSelection
获取SharedPreferences
,我认为您知道如何做到这一点。此外,您还需要在每次更改时设置新值:
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
((TextView) parentView.getChildAt(0)).setTextColor(Color.BLACK);
selected = parentView.getItemAtPosition(position).toString();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("selectionIndex", position);
editor.apply();
}
SharedPreferences sharedPreferences
应该是您的Framgent中的一个字段,您将在onAttach
或您认为合适的位置初始化该字段:
@Override
protected void onAttach(Context context) {
super.onAttach(context);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
答案 1 :(得分:0)
我使用过editor.putInt(&#34; VALUE&#34;,spinner.getSelectedItemPosition());