我想从sharedPreferences中删除我在listView中选择的项目。但我不知道如何将它包含在我的代码中。我已经尝试过很多我从互联网上看过的代码,但这会让我的应用程序出错。有人可以给我一个想法吗?大帮助。谢谢
这是MySharedPreference类:
public class MySharedPreference {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
// Context
private Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "pref";
private static final String SCORES = "scores";
public MySharedPreference(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void saveHighScoreList(String scoreString) {
editor.putString(PREF_NAME, scoreString);
editor.commit();
}
public String getHighScoreList() {
return pref.getString(PREF_NAME, "");
}
}
这是我的ListViewAdapter:
public class ListViewAdapter_History extends ArrayAdapter<Input> {
private Activity activity;
public ListViewAdapter_History(Activity activity, int resource, List<Input> scores) {
super(activity, resource, scores);
this.activity = activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.item_listview, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
Input score = getItem(position);
holder.score.setText(score.getScore());
return convertView;
}
private static class ViewHolder {
private TextView score;
public ViewHolder(View v) {
score = (TextView) v.findViewById(R.id.score);
}
}
}
我希望它执行删除共享首选项到我的另一个类,其中删除按钮是,但我仍然在想我将选择onItemLongClick或一个简单的删除按钮。
PS。我希望你明白我想要达到的目标。感谢
答案 0 :(得分:0)
您必须在适配器中实例化MySharedPreference
类并在MySharedPreference
类中创建一个删除方法:
public void deletePrefs(String score){
editor.remove(score);
}
并在您的适配器中:
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s=getItem(position).getScore().getText().toString();
presfs.deletePrefs(s)
}
});