使用ListView保存历史输入记录

parcool 2015-03-05

android应用中,经常需要保存用户的输入记录,以保证用户下次输入时可以在历史记录中直接选择可能要输入的值,这样就提高了用户的体验性!

保存用户输入的列表项:

<ListView android:id="@+id/listView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:divider="#dcdcdc"
       android:dividerHeight="1px"
       android:headerDividersEnabled="false"  />
   <Button android:id="@+id/clear"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="清除历史记录" />

保存用户输入的代码(Activity):

SharedPreferences preferences = getActivity().getSharedPreferences("select", getActivity().MODE_WORLD_READABLE);;
SharedPreferences.Editor editor = preferences.edit();

String history = preferences.getString("select", "");
StringBuilder sb = new StringBuilder(history);
sb.append(city + ",");
if(!history.contains(city + ",")) {
	editor.putString("select", sb.toString());
	editor.commit();
}
getActivity().finish();

取出历史记录,并显示的Activity:

preferences = getActivity().getSharedPreferences("select", getActivity().MODE_WORLD_READABLE);
editor = preferences.edit();

String city = preferences.getString("select", "");
if(city.equals("") || city==null) {
	clear.setVisibility(4);
}
String[] citys = city.split(",");
adapter = new ArrayAdapter<String>(getActivity(), R.layout.array_item, citys);
lv.setAdapter(adapter);

而清空历史记录的代码如下:

clear.setOnClickListener(new OnClickListener() {
	@Override
	public void onClick(View v) {
		editor.clear();
		editor.commit();
		lv.setAdapter(null);
		v.setVisibility(4);
	}
});

相关推荐

开发中的点点滴滴 / 0评论 2018-03-30