我在课堂上使用共享首选项时遇到问题。我的代码和程序流程:
我的活动中有Spinner
。我正在实现我自己的OnItemSelectedListener:
MyOnItemSelectedListener.java
public class MyOnItemSelectedListener implements OnItemSelectedListener {
SharedPreferences pref;
Editor editor;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
//parent.setSelection(7);
Toast.makeText(parent.getContext(), "Selected Country : " + parent.getItemIdAtPosition(pos), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
我从我的活动中调用上述课程:
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new MyOnItemSelectedListener());
到目前为止一切都那么好。我想要的是将spinner1
上的所选项目保存到用户的偏好设置(并从保存的值中设置)。
在活动中我正在使用我的共享首字母:
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
但是在类中,上下文不存在!当用户选择微调器上的项目时,是否有任何帮助检索/保存pref?
谢谢!
答案 0 :(得分:1)
为您的侦听器创建一个构造函数,并将Context
传递给它:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
SharedPreferences pref;
Editor editor;
public MyOnItemSelectedListener(Context context) {
pref = context.getSharedPreferences("MyPref", 0);
}
// rest of your code
}