使用ListView保存历史输入记录
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); } });
相关推荐
chenjinlong 2020-02-19
83580494 2013-07-19
langjiao 2013-07-16
kiduo0 2013-07-10
gongzhiyao0 2010-11-15
bigdatazx 2010-11-05
Urchindong 2011-08-01
peixiaopao 2011-08-21
MeOrdinary 2014-05-13
magic00 2019-10-21
guizhongyun 2011-09-27
csuhanshuai 2015-03-30
Sunanang 2015-03-30
snailbing 2015-04-23
huohu00 2015-04-22
toperfect 2015-07-01
nickey 2012-01-29
Rgenxiao 2012-01-26
满城风絮 2011-12-03