我有自定义SharedPreference类,我试图从我的自定义SharedPrefecenses类得到的字符串。我在getView方法时遇到错误“PRF =新PrefManager(上下文);”
我能做些什么,我一直在寻找2天。
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Secur-transact";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getString(String PREF_NAME) {
if(pref.contains(PREF_NAME)){
return pref.getString(PREF_NAME,null);
}
return "";
}
}
我试图让适配器视图getString方法。
public class CustomListAdapter extends BaseAdapter {
PrefManager prf;
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
prf = new PrefManager(context); // I GOT ERROR IN HERE
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
TextView name = (TextView) convertView.findViewById(R.id.name);
if (prf.getString("ColorName").equals("RED")) {
name.setBackgroundResource(R.color.primaryLightColorRed);
name.setTextColor(R.color.colorWhite);
}
这里初始化
public class SampleClass extends Fragment {
private List<ModelsProps> modelsPropsList = new ArrayList<ModelsProps>();
public SampleClass () {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final ListView listView = (ListView) rootView.findViewById(R.id.list);
final CustomListAdapter adapter = new CustomListAdapter(getActivity(), modelsPropsList);
listView.setAdapter(adapter);
你可能不进行初始化变量context
。
刚刚尝试改变路线:
prf = new PrefManager(context);
至:
prf = new PrefManager(parent.getContext());
你可以通过从片段上下文中构造你的适配器,然后从适配器通过它的偏好类。