使用EditText和SharedPreferences实现搜索历史记录提示功能

一、实现效果如下

1.第一次进入搜索界面

使用EditText和SharedPreferences实现搜索历史记录提示功能_第1张图片

2.点击加号,将文字赋值给EditText,点击搜索进入搜索

使用EditText和SharedPreferences实现搜索历史记录提示功能_第2张图片

3.点击EditText中的清除按钮,将显示第一张图片


二、代码如下

1.布局文件

activity_search.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical" >

    <include layout="@layout/titlebar_search" />

    <FrameLayout
        android:id="@+id/content_frame_search"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </FrameLayout>

</LinearLayout>
titlebar_search.xml

<?xml version="1.0" encoding="utf-8"?>

<!-- 首页 类似actionBar -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/activity_search_title_bg"
        android:orientation="horizontal" >


        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginBottom="3dp"
            android:layout_marginLeft="3dp"
            android:layout_marginRight="3dp"
            android:layout_marginTop="3dp"
            android:layout_weight="1"
            android:gravity="center_vertical" >

            <EditText
                android:id="@+id/editText_search_searchactivity"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/search_edittext_selector"
                android:ems="15"
                android:hint="  search"
                android:imeOptions="actionSearch"
                android:singleLine="true"
                android:textColor="#000000"
                android:textCursorDrawable="@null" 
                />

            <ImageView
                android:id="@+id/ivDeleteText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerInParent="true"
                android:paddingRight="5dp"
                android:src="@drawable/xbtn"
                android:visibility="gone" />
        </RelativeLayout>

        <ImageView
            android:id="@+id/image_search_searchactivity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:padding="0dp"
            android:src="@drawable/ic_search_menu" />
    </LinearLayout>

</RelativeLayout>

2.代码

SearchActivity.java

package com.chinabuye.android.activity;

import java.util.ArrayList;
import java.util.Arrays;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.chinabuye.android.R;
import com.chinabuye.android.adapter.SearchAutoAdapter;
import com.chinabuye.android.bean.SearchAutoData;
import com.chinabuye.android.fragment.HomeFragment;
import com.chinabuye.android.fragment.SearchFragment;
import com.chinabuye.android.fragment.SearchHistoryFragment;
import com.chinabuye.android.scrollview.Constants;
import com.chinabuye.android.slidingmenu.MyDrawerView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

/**
 * 
 * 最初没有获得焦点时,推荐的fragment 获得焦点时,显示的是历史fragment 点击搜索后,显示的是产品fragment
 * 
 * @author Administrator
 * 
 */
public class SearchActivity extends FragmentActivity implements OnClickListener {
	public static final String SEARCH_HISTORY = "search_history";
	protected SlidingMenu side_drawer;
	private FragmentManager manager;
	private FragmentTransaction transaction;
	// 搜索
	private EditText edit_search;
	private ImageView image_search;
	//删除
	private ImageView ivDeleteText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		/**
		 * 准备工作
		 */
		/*** 管理Activity ****/
		manageActivity();
		side_drawer = new MyDrawerView(this).initSlidingMenu();// 初始化侧边栏
		manager = getSupportFragmentManager();

		/**
		 * 初始化activity控件
		 */
		initView();
		/**
		 * 获得焦点时,显示的碎片
		 */
		initHistoryFragment();
	}

	/** 初始化显示的fragment **/
	private void initHistoryFragment() {
		transaction = manager.beginTransaction();
		Fragment fragment = new SearchHistoryFragment();
		Bundle bundle = new Bundle();
		fragment.setArguments(bundle);
		transaction.replace(R.id.content_frame_search, fragment, "history").commit();
	}

	private void manageActivity() {
		ActivityInstanceManager.getActivityInstanceManager().addActivity(this);
	}

	private void initView() {
		//搜索框
		edit_search = (EditText) this.findViewById(R.id.editText_search_searchactivity);
		//搜索按钮
		image_search = (ImageView) this.findViewById(R.id.image_search_searchactivity);
		image_search.setOnClickListener(this);
		//删除按钮
		ivDeleteText = (ImageView) this.findViewById(R.id.ivDeleteText);
		ivDeleteText.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.image_search_searchactivity:
			saveSearchHistory();//保存输入记录
			goSearch();//进行搜索
			break;
		case R.id.ivDeleteText:
			edit_search.setText("");
			//切换到搜索碎片
			initHistoryFragment();
			break;
		default:
			break;
		}

	}

	/**
	 * 切换到产品碎片
	 * 
	 * @param q
	 */
	private void changeToFragment(String q) {
		transaction = manager.beginTransaction();
		Fragment fragment = new SearchFragment();
		Bundle bundle = new Bundle();
		bundle.putString("q", q);
		fragment.setArguments(bundle);
		transaction.replace(R.id.content_frame_search, fragment, "TAG" + q).commit();
	}

	/**** 显示键盘 *******/
	public void showSoftKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
	}

	/****** 隐藏键盘 ********/
	private void hideSoftKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	/***** 进行搜索 *******/
	private void goSearch() {
		/*隐藏软键盘*/
		hideSoftKeyboard();
		String q = edit_search.getText().toString().trim();
		if (q != null && q.length() > 0) {
			changeToFragment(q);
		}
	}

	/*
	 * 保存搜索记录
	 */
	private void saveSearchHistory() {
		String text = edit_search.getText().toString().trim();
		if (text.length() < 1) {
			return;
		}
		SharedPreferences sp = getSharedPreferences(SEARCH_HISTORY, 0);
		String longhistory = sp.getString(SEARCH_HISTORY, "");
		String[] tmpHistory = longhistory.split(",");
		ArrayList<String> history = new ArrayList<String>(
				Arrays.asList(tmpHistory));
		if (history.size() > 0) {
			int i;
			for (i = 0; i < history.size(); i++) {
				if (text.equals(history.get(i))) {
					history.remove(i);
					break;
				}
			}
			history.add(0, text);
		}
		if (history.size() > 0) {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < history.size(); i++) {
				sb.append(history.get(i) + ",");
			}
			sp.edit().putString(SEARCH_HISTORY, sb.toString()).commit();
		} else {
			sp.edit().putString(SEARCH_HISTORY, text + ",").commit();
		}
	}
}
SearchFragment.java,关系不大,纯粹展示数据,代码略:

SearchHistoryFragment.java,密切相关,代码如下:

package com.chinabuye.android.fragment;

import cn.sharesdk.framework.m;

import com.chinabuye.android.R;
import com.chinabuye.android.adapter.SearchAutoAdapter;
import com.chinabuye.android.bean.SearchAutoData;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class SearchHistoryFragment extends Fragment implements OnClickListener {
	private Activity activity;
	private EditText edit_search;
	private SearchAutoAdapter mSearchAutoAdapter;
	private ListView mAutoListView;
	private ImageView image_search;
	private ImageView ivDeleteText;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		/***** fragment所在的activity的控件 *****/
		//搜索框
		//搜索框内容变化时,显示历史内容也发生变化
		edit_search = (EditText) activity.findViewById(R.id.editText_search_searchactivity);
		edit_search.addTextChangedListener(mTextChangeListener);
		edit_search.setOnKeyListener(onKeyListener);
		//删除按钮
		ivDeleteText = (ImageView) activity.findViewById(R.id.ivDeleteText);
		//搜索按钮
		image_search = (ImageView) activity.findViewById(R.id.image_search_searchactivity);

		/****** fragment中的控件 *****/
		View view = inflater.inflate(R.layout.fragment_search_history, null);
		mAutoListView = (ListView) view.findViewById(R.id.auto_listview);
		mSearchAutoAdapter = new SearchAutoAdapter(activity, -1, this);
		mAutoListView.setAdapter(mSearchAutoAdapter);
		mAutoListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) {
				/**
				 * 点击列表时,根据position取出对应的文字,并赋值给文本框,同时响应搜索按钮的点击事件
				 */
				SearchAutoData data = (SearchAutoData) mSearchAutoAdapter.getItem(position);
				edit_search.setText(data.getContent());
				image_search.performClick();
			}
		});
		return view;
	}

	/**** 文本监听器 ******/
	private TextWatcher mTextChangeListener = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			/**
			 * 根据输入的内容对显示的列表示数据进行过滤
			 */
			mSearchAutoAdapter.performFiltering(s);
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			/**
			 * 根据文本款的内容是否为空,隐藏和显示删除按钮
			 */
			if (s.length() == 0) {
				ivDeleteText.setVisibility(View.GONE);
			} else {
				ivDeleteText.setVisibility(View.VISIBLE);
			}
		}
	};

	/**** EditText按键监听 ****/
	private OnKeyListener onKeyListener = new OnKeyListener() {

		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			/**
			 * 如果用户点击了手机键盘的enter键,响应搜索按钮的点击事件
			 */
			if (keyCode == KeyEvent.KEYCODE_ENTER) {
				image_search.performClick();
				return true;
			}
			return false;
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		/**
		 * 点击的如果是列表项目中的加号按钮,将加号按钮所在行的文字赋值给输入框
		 */
		case R.id.auto_add:
			SearchAutoData data = (SearchAutoData) v.getTag();
			edit_search.setText(data.getContent());
			break;
		}
	}
}
fragment_search_history.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/auto_listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible" >
    </ListView>

</LinearLayout>
SearchAutoData.java,对每一行的历史记录设置属性,是一个业务Bean

package com.chinabuye.android.bean;

public class SearchAutoData {

	private String id ="";
	private String content = "";
	public String getId() {
		return id;
	}
	public SearchAutoData setId(String id) {
		this.id = id;
		return this;
	}
	public String getContent() {
		return content;
	}
	public SearchAutoData setContent(String content) {
		this.content = content;
		return this;
	}
}

SearchAutoAdapter.java适配器,不用做任何修改,直接使用:

package com.chinabuye.android.adapter;

import java.util.ArrayList;
import java.util.List;

import com.chinabuye.android.R;
import com.chinabuye.android.activity.SearchActivity;
import com.chinabuye.android.bean.SearchAutoData;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class SearchAutoAdapter extends BaseAdapter {
	private Context mContext;
	private ArrayList<SearchAutoData> mOriginalValues;// 所有的Item
	private List<SearchAutoData> mObjects;// 过滤后的item
	private final Object mLock = new Object();
	private int mMaxMatch = 10;// 最多显示多少个选项,负数表示全部
	private OnClickListener mOnClickListener;

	public SearchAutoAdapter(Context context, int maxMatch,
			OnClickListener onClickListener) {
		this.mContext = context;
		this.mMaxMatch = maxMatch;
		this.mOnClickListener = onClickListener;
		initSearchHistory();
		mObjects = mOriginalValues;
	}

	@Override
	public int getCount() {
		Log.i("cyl", "getCount");
		return null == mObjects ? 0 : mObjects.size();
	}

	@Override
	public Object getItem(int position) {
		return null == mObjects ? 0 : mObjects.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		AutoHolder holder;
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.auto_seach_list_item, parent, false);
			holder = new AutoHolder();
			holder.content = (TextView) convertView
					.findViewById(R.id.auto_content);
			holder.addButton = (TextView) convertView
					.findViewById(R.id.auto_add);
			holder.autoImage = (TextView) convertView
					.findViewById(R.id.auto_image);
			convertView.setTag(holder);
		} else {
			holder = (AutoHolder) convertView.getTag();
		}

		SearchAutoData data = mObjects.get(position);
		holder.content.setText(data.getContent());
		holder.addButton.setTag(data);
		holder.addButton.setOnClickListener(mOnClickListener);
		return convertView;
	}

	/**
	 * 读取历史搜索记录
	 */
	public void initSearchHistory() {
		SharedPreferences sp = mContext.getSharedPreferences(
				SearchActivity.SEARCH_HISTORY, 0);
		String longhistory = sp.getString(SearchActivity.SEARCH_HISTORY, "");
		String[] hisArrays = longhistory.split(",");
		mOriginalValues = new ArrayList<SearchAutoData>();
		if (hisArrays.length == 1) {
			return;
		}
		for (int i = 0; i < hisArrays.length; i++) {
			mOriginalValues.add(new SearchAutoData().setContent(hisArrays[i]));
		}
	}

	/**
	 * 匹配过滤搜索内容
	 * 
	 * @param prefix
	 *            输入框中输入的内容
	 */
	public void performFiltering(CharSequence prefix) {
		if (prefix == null || prefix.length() == 0) {//搜索框内容为空的时候显示所有历史记录
			synchronized (mLock) {
				mObjects = mOriginalValues;
			}
		} else {
			String prefixString = prefix.toString().toLowerCase();
			int count = mOriginalValues.size();
			ArrayList<SearchAutoData> newValues = new ArrayList<SearchAutoData>(
					count);
			for (int i = 0; i < count; i++) {
				final String value = mOriginalValues.get(i).getContent();
				final String valueText = value.toLowerCase();
				if (valueText.contains(prefixString)) {

				}
				if (valueText.startsWith(prefixString)) {
					newValues.add(new SearchAutoData().setContent(valueText));
				} else {
					final String[] words = valueText.split(" ");
					final int wordCount = words.length;
					for (int k = 0; k < wordCount; k++) {
						if (words[k].startsWith(prefixString)) {
							newValues.add(new SearchAutoData()
									.setContent(value));
							break;
						}
					}
				}
				if (mMaxMatch > 0) {
					if (newValues.size() > mMaxMatch - 1) {
						break;
					}
				}
			}
			mObjects = newValues;
		}
		notifyDataSetChanged();
	}

	private class AutoHolder {
		TextView content;
		TextView addButton;
		TextView autoImage;
	}
}

auto_seach_list_item.xml,搜索历史记录每一行的布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="40dp" >

    <TextView
        android:id="@+id/auto_add"
        android:layout_width="30dp"
        android:layout_height="fill_parent"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="@string/jiahao"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/auto_image"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="@drawable/clock" />

    <TextView
        android:id="@+id/auto_content"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="20dp"
        android:layout_toRightOf="@+id/auto_image"
        android:gravity="center"
        android:text="@string/search_history"
        android:textSize="14sp" />

</RelativeLayout>





你可能感兴趣的:(EditText,自动提示,sharepreference,搜索历史)