AutoCompleteTextView记录历史记录
?package org.yaoming.read_his;
import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.ArrayAdapter;import android.widget.AutoCompleteTextView;public class AutoTextView extends Activity {private AutoCompleteTextView autoTv;private static final String HISTORY = "search_history";public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);autoTv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);initAutoComplete("history", autoTv);findViewById(R.id.button1).setOnClickListener(new OnClickListener() {public void onClick(View v) {saveHistoryToSharedPreference("history", autoTv);// 这里可以设定:当搜索成功时,才执行保存操作}});}/** * 初始化AutoCompleteTextView,最多显示5项提示,使 AutoCompleteTextView在一开始获得焦点时自动提示 * * @param field * 保存在sharedPreference中的字段名 * @param auto * 要操作的AutoCompleteTextView */private void initAutoComplete(String field, AutoCompleteTextView auto) {SharedPreferences sp = getSharedPreferences(HISTORY, 0);String longhistory = sp.getString("history", "");String[] hisArrays = longhistory.split(",");ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, hisArrays);// 只保留最近的50条的记录if (hisArrays.length > 50) {String[] newArrays = new String[50];System.arraycopy(hisArrays, 0, newArrays, 0, 50);adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, newArrays);}auto.setOnClickListener(new OnClickListener() {public void onClick(View v) {autoTv.showDropDown();}});auto.setAdapter(adapter);auto.setDropDownHeight(200);// 下拉的高度auto.setThreshold(1);auto.setCompletionHint("搜索记录");// 提示字段}/** * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段 * * @param field * 保存在sharedPreference中的字段名 * @param auto * 要操作的AutoCompleteTextView */private void saveHistoryToSharedPreference(String field,AutoCompleteTextView auto) {String text = auto.getText().toString();SharedPreferences sp = getSharedPreferences(HISTORY, 0);String longhistory = sp.getString(field, "");if (!longhistory.contains(text + ",")) {// 不存在重复的StringBuilder sb = new StringBuilder(longhistory);sb.insert(0, text + ",");sp.edit().putString("history", sb.toString()).commit();}initAutoComplete("history", autoTv);}}?