---
title: "AutoCompleteTextView记录历史记录"
author: "AndLi"
date: "2012-04-20T23:26:26Z"
tags: []
categories: ["移动开发"]
slug: "autocompletetextview"
draft: false
lastmod: "2012-04-20T23:26:26Z"
id: 1492487
url: "https://andli.iteye.com/blog/1492487"
---

![](http://dl.iteye.com/upload/attachment/0066/9417/6e3ac676-89b6-327f-af9e-b8f4e970ed1f.jpg)  
 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);

	}
}
```