Android,适配器中的sharedpreferences

lit*_*bat 3 java android android-arrayadapter sharedpreferences android-studio

在列表适配器getview方法中使用sharedpreferences的最佳方法是什么?我必须使用来自sharedpreferences的一些值,但不知道如何获取它。我试过了:

pref = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)

它在活动中起作用,并且:

SharedPreferences pref = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)

可以分段工作,但都不能在listadapter中工作。

小智 5

您可以Context在的构造函数中将as作为字段传递,ListAdapter并使用该context字段获取SharedPreferences