android搜索功能以及显示历史纪录带清除按钮

原创 2015年04月14日 18:46:53

其实这部分主要是实现很多逻辑功能顺序,点击搜索出来的内容显示在一个listview中,然后历史记录又显示在另一个listview中,只要设置listview.setVisibility(View.GONE/VISIBLE),实现切换,就差不多了,以及清除按钮的显示,详细的解释会在代码中呈现。代码比较繁琐,毕竟能力有限,纯粹是根据自己想法实现的逻辑功能,还有写地方不够完美,仅供参考。

首先是主界面SearchActivity类:

<pre name="code" class="java">package com.example.activity;

import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;

import com.example.adapter.SearchHistoryAdapter;
import com.example.adapter.SearchShowLvAdapter;
import com.example.db.HistoryHelper;
import com.example.domain.Contance;
import com.example.domain.ContanceKey;
import com.example.domain.HistoryShowBean;
import com.example.domain.ImportContance;
import com.example.domain.JingdianName;
import com.example.domain.SearchShowBean;
import com.example.utils.SearchClearEditText;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SearchActivity extends Activity implements OnClickListener,
		OnItemClickListener {

	private ImageButton ib_back_normal; // 搜索框左侧返回按钮
	private TextView tv_search; // 搜索框右边的搜索字样
	SearchClearEditText clear_et;
	private ListView lv_search_xianshi, lv_search_history;
	private Button clear_search_history_btn;

	// 初始化数据库打开器
	HistoryHelper helper;
	private SearchHistoryAdapter his_adapter;

	private List<SearchShowBean> sea_data;
	private List<HistoryShowBean> his_data;
	static List<String> list = new ArrayList<String>();

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// 点击清除记录按钮,刷新界面
				his_adapter.refresh(queryHistoryData());
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置无标题,使用自己的布局
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.clear_et_activity);

		init();

	}

	/*
	 * 初始化组件
	 */
	private void init() {
		ib_back_normal = (ImageButton) findViewById(R.id.ib_back_normal);
		tv_search = (TextView) findViewById(R.id.tv_search);
		clear_et = (SearchClearEditText) findViewById(R.id.et_clear);
		clear_search_history_btn = (Button) findViewById(R.id.clear_search_history_btn);

		lv_search_xianshi = (ListView) findViewById(R.id.search_xianshi_lv);
		lv_search_history = (ListView) findViewById(R.id.search_history_lv);

		his_data = queryHistoryData();

		his_adapter = new SearchHistoryAdapter(his_data, this);
		lv_search_history.setAdapter(his_adapter);

		ib_back_normal.setOnClickListener(this);
		tv_search.setOnClickListener(this);
		clear_search_history_btn.setOnClickListener(this);

		lv_search_history.setOnItemClickListener(this);
		lv_search_xianshi.setOnItemClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ib_back_normal:
			Intent intent = new Intent(SearchActivity.this, MainActivity.class);
			startActivity(intent);
			SearchActivity.this.finish(); // 结束当前界面
			// lv_search_xianshi.setVisibility(View.GONE);
			break;
		case R.id.tv_search: // 点击搜索按钮
			/*
			 * 点击搜索按钮先清空,是因为数据使用list集合保存的,如果搜索一个景点出来数据后,
			 * 直接搜索另一个,就会叠加,所以先清空,这样每次显示的都是最新的
			 */
			list.removeAll(list);
			// 点击搜索按钮,使得显示搜索结果的listview显示出来
			lv_search_xianshi.setVisibility(View.VISIBLE);
			lv_search_history.setVisibility(View.GONE);
			clear_search_history_btn.setVisibility(View.GONE);

			String search = clear_et.getText().toString().trim();
			int count = 0;
			for (int i = 0; i < JingdianName.names.length; i++) {
				if (JingdianName.names[i].contains(search) == true) {
					list.add(JingdianName.names[i]);
					count++;
				}
			}
			if (count == 0) { // 如果一个也没有查到,就显示没有景点
				list.removeAll(list); // 清空集合数据,重新查询
				getData(list, lv_search_xianshi);
				Toast.makeText(getApplicationContext(), "没有该景点",
						Toast.LENGTH_SHORT).show();
			} else { // 有数据就显示
				getData(list, lv_search_xianshi);
			}

			// 插入数据库数据
			insertHistory(search);

			break;

		case R.id.clear_search_history_btn: // 点击清除历史记录按钮
			deleteHistory();
			break;
		default:
			break;
		}
	}

	/*
	 * 删除历史记录
	 */
	private void deleteHistory() {
		helper = new HistoryHelper(getApplicationContext());
		SQLiteDatabase db = helper.getWritableDatabase();
		// 删除表。
		db.execSQL("delete from " + Contance.HISTORY_TABLENAME);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// 此处handler发送一个message,用来更新ui
				Message msg = new Message();
				msg.what = 1;
				handler.sendMessage(msg);
			}
		}).start();
		// his_adapter.refresh(queryHistoryData());
		db.close();
	}

	/*
	 * 插入历史记录,点击按钮,获得edittext的值,写到数据库
	 */
	private void insertHistory(String search) {
		helper = new HistoryHelper(getApplicationContext());
		// 插入数据库
		SQLiteDatabase db = helper.getWritableDatabase();
		Log.i("create", "数据库表history创建成功");
		int count = 0;
		// 查询数据库,判断edittext的内容是否已经存在,如果存在了,就不写了,如果不存在,就插入数据库
		// 取回查询存放history表的h_name列的list集合
		List<String> list = queryHistorySql();
		for (int i = 0; i < list.size(); i++) {
			// 获取搜索框的输入内容,和数据已经存在的记录比对,如果有一样的,就count增加;
			if (list.get(i).equals(search)) {
				count++;
			}
		}
		// 如果count == 0,说明没有重复的数据,就可以插入数据库history表中
		if (count == 0) {
			db.execSQL("insert into " + Contance.HISTORY_TABLENAME
					+ " values(?,?)", new Object[] { null, search });
			Log.i("create", "数据库表history数据插入成功");
		} else {
			// Toast.makeText(getApplicationContext(), "已存在",
			// Toast.LENGTH_SHORT)
			// .show();
		}

		db.close();
	}

	/*
	 * 查询数据库的h_name一列,然后放到list集合中,用于判断是否插入数据
	 */
	private List<String> queryHistorySql() {
		helper = new HistoryHelper(getApplicationContext());
		List<String> list = new ArrayList<String>();
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from "
				+ Contance.HISTORY_TABLENAME, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			// 查询数据库,取出h_name这一列,然后全部放到list集合中,在前面调用此方法的时候,用来判断
			String name = cursor.getString(cursor.getColumnIndex("h_name"));
			list.add(name);
			cursor.moveToNext();
		}

		db.close();
		// 返回一个list集合
		return list;
	}

	/*
	 * 点击搜索按钮后,查询出来的结果
	 */
	private void getData(List<String> list, ListView listView) {
		sea_data = new ArrayList<SearchShowBean>();
		for (int i = 0; i < list.size(); i++) {
			SearchShowBean bean = new SearchShowBean();
			bean.setJingdian(list.get(i));
			bean.setImage(getResources().getDrawable(
					R.drawable.umeng_socialize_search_icon));
			sea_data.add(bean);
		}
		listView.setAdapter(new SearchShowLvAdapter(this, sea_data));
	}

	// 将每一行的数据封装成一个HistoryShowBean对象,然后放到his_list中
	private List<HistoryShowBean> queryHistoryData() {
		helper = new HistoryHelper(getApplicationContext());
		List<HistoryShowBean> his_list = new ArrayList<HistoryShowBean>();
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor his_c = db.rawQuery("select * from "
				+ Contance.HISTORY_TABLENAME, null);

		his_c.moveToFirst();
		while (!his_c.isAfterLast()) {
			int h_id = his_c.getInt(his_c.getColumnIndex("_id"));
			String h_name = his_c.getString(his_c.getColumnIndex("h_name"));

			// 用一个HistoryShowBean类来封装得到的数据
			final HistoryShowBean his_bean = new HistoryShowBean();
			his_bean.setJingdian(h_name);
			his_bean.setImage(getResources().getDrawable(
					R.drawable.history_icon));
			his_list.add(his_bean);
			his_c.moveToNext();
		}
		if (his_list.size() == 0) {
			clear_search_history_btn.setVisibility(View.GONE);
		}
		db.close();
		return his_list;

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {// 按下的如果是BACK,同时没有重复
			Intent intent = new Intent(SearchActivity.this, MainActivity.class);
			startActivity(intent);
			SearchActivity.this.finish();
			// 这里不需要执行父类的点击事件,所以直接return
			return true;
		}
		// 继续执行父类的其他点击事件
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		switch (parent.getId()) { // 获得listview的id
		case R.id.search_xianshi_lv: // 显示listview
			// 获得当前点击的item
			view = lv_search_xianshi.getChildAt(position);
			// 获得item中的textview控件,并初始化
			TextView tv = (TextView) view.findViewById(R.id.search_xianshi_tv);
			// 获得textview的值
			String str = tv.getText().toString().trim();
			// 进行数据库查询并且跳转
			listViewJump(str);
			break;
		case R.id.search_history_lv:
			view = lv_search_history.getChildAt(position);
			TextView tv1 = (TextView) view.findViewById(R.id.search_history_tv);
			String str1 = tv1.getText().toString().trim();
			String string = null;
			// 之前已经把数据库的列“mingcheng”的值已经放到了一个数组中
			// 判断点击的item中的textview的值在mingcheng中是否存在,如果存在,就把那个值给了数据库查询
			Log.i("searchAcitivity", "11111");
			// Boolean boolean1 = null;
			int count1 = 0;
			for (int i = 0; i < JingdianName.names.length; i++) {
				Log.i("searchAcitivity", "22222");
				if (JingdianName.names[i].equals(str1)) {
					Log.i("searchAcitivity", "33333");
					string = JingdianName.names[i];
					// 方法放在for循环外面会有问题
					listViewJump(string);
					Log.i("searchAcitivity", "44444");
					// boolean1 = true;
					count1++;
					break;
				}
			}
			if (count1 == 0) {
				Log.i("searchAcitivity", "88888");
				Toast.makeText(getApplicationContext(), "没有该景点",
						Toast.LENGTH_SHORT).show();
			}
			Log.i("searchAcitivity", "99999");

			break;
		default:
			break;
		}
	}

	private void listViewJump(String str) {
		String sql = "select * from jingdian where mingcheng = '" + str + "'";
		Cursor c = Contance.SQLITE.rawQuery(sql, null);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			ImportContance.MINGCHENG = c.getString(c
					.getColumnIndex("mingcheng"));
			ImportContance.JIESHAO = c.getString(c.getColumnIndex("jieshao"));
			ImportContance.LEIXING = c.getString(c.getColumnIndex("leixing"));
			ImportContance.JIJIE = c.getString(c.getColumnIndex("jijie"));
			ImportContance.JIANYI = c.getString(c.getColumnIndex("jianyi"));
			ImportContance.MENPIAO = c.getString(c.getColumnIndex("menpiao"));
			ImportContance.SHIJIAN = c.getString(c.getColumnIndex("shijian"));
			ImportContance.DIZHI = c.getString(c.getColumnIndex("dizhi"));
			c.moveToNext();
		}

		c.close();

		Intent intent = new Intent(SearchActivity.this, SingleActivity.class);
		intent.putExtra(ContanceKey.KEY_MINGCHENG, ImportContance.MINGCHENG);
		intent.putExtra(ContanceKey.KEY_JIESHAO, ImportContance.JIESHAO);
		intent.putExtra(ContanceKey.KEY_LEIXING, ImportContance.LEIXING);
		intent.putExtra(ContanceKey.KEY_JIJIE, ImportContance.JIJIE);
		intent.putExtra(ContanceKey.KEY_JIANYI, ImportContance.JIANYI);
		intent.putExtra(ContanceKey.KEY_MENPIAO, ImportContance.MENPIAO);
		intent.putExtra(ContanceKey.KEY_SHIJIAN, ImportContance.SHIJIAN);
		intent.putExtra(ContanceKey.KEY_DIZHI, ImportContance.DIZHI);
		startActivity(intent);
		SearchActivity.this.finish();
	}
}




下来就是主界面的布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/layout_clear_et"
        android:layout_width="fill_parent"
        android:layout_height="44dp"
        android:background="@drawable/nav_bg"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/ib_back_normal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|left"
            android:background="@drawable/search_et_back" />

        <com.example.utils.SearchClearEditText
            android:id="@+id/et_clear"
            android:layout_width="wrap_content"
            android:layout_height="32dp"
            android:layout_gravity="center_vertical"
            android:layout_weight="0.91"
            android:background="@drawable/et_search_clear_attr"
            android:drawableLeft="@drawable/umeng_socialize_search_icon"
            android:drawableRight="@drawable/search_clear"
            android:ems="10"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:hint="请输入景点"
            android:paddingLeft="5dp"
            android:paddingRight="3dp"
            android:singleLine="true" />

        <TextView
            android:id="@+id/tv_search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:clickable="true"
            android:padding="5dp"
            android:text="搜索"
            android:textColor="#FFFFFF"
            android:textSize="18dp" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/search_framelayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

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

        <ListView
            android:id="@+id/search_xianshi_lv"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:visibility="gone" >
        </ListView>
    </FrameLayout>

    <Button
        android:id="@+id/clear_search_history_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/delete_history_icon"
        android:text="清除历史记录"
        android:visibility="visible" >
    </Button>

</LinearLayout>

历史记录显示的listview的适配器adapter类:

public class SearchHistoryAdapter extends BaseAdapter {

	private Context mContext;
	private List<HistoryShowBean> mdata;

	public SearchHistoryAdapter(List<HistoryShowBean> data, Context context) {
		this.mContext = context;
		this.mdata = data;
	}

	// 刷新适配器,更新数据
	public void refresh(List<HistoryShowBean> data) {
		this.mdata = data;
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return mdata.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = View.inflate(mContext,
					R.layout.search_history_lv_item, null);
			holder = new ViewHolder();
			holder.textView = (TextView) convertView
					.findViewById(R.id.search_history_tv);
			holder.imageView = (ImageView) convertView
					.findViewById(R.id.search_history_iv);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		HistoryShowBean bean = mdata.get(position);
		holder.textView.setText(bean.getJingdian());
		holder.imageView.setImageDrawable(bean.getImage());

		return convertView;
	}

	private static class ViewHolder {
		ImageView imageView;
		TextView textView;
	}

}

点击搜索按钮当前显示的listview的适配器adapter类:

public class SearchShowLvAdapter extends BaseAdapter {

	private Context mContext;
	private List<SearchShowBean> mdata;

	public SearchShowLvAdapter(Context context, List<SearchShowBean> data) {
		this.mContext = context;
		this.mdata = data;
	}

	@Override
	public int getCount() {
		return mdata.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			// 如果视图等于null,就给个布局
			convertView = View.inflate(mContext,
					R.layout.search_xianshi_lv_item, null);
			// 初始化hodler
			holder = new ViewHolder();
			// 每项的视图布局是一样的
			holder.textView = (TextView) convertView
					.findViewById(R.id.search_xianshi_tv);
			holder.imageView = (ImageView) convertView
					.findViewById(R.id.search_xianshi_iv);
			// 给View添加数据,然后用getTag()取出来
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		SearchShowBean bean = mdata.get(position);
		holder.textView.setText(bean.getJingdian());
		holder.imageView.setImageDrawable(bean.getImage());

		return convertView;
	}

	/*
	 * 临时的储存器
	 */
	private static class ViewHolder {
		TextView textView;
		ImageView imageView;
	}

}

对应的两个javabean类:

public class HistoryShowBean {
	private int _id;
	private String jingdian;
	private Drawable image;

	public int get_id() {
		return _id;
	}

	public void set_id(int _id) {
		this._id = _id;
	}

	public Drawable getImage() {
		return image;
	}

	public void setImage(Drawable image) {
		this.image = image;
	}

	public String getJingdian() {
		return jingdian;
	}

	public void setJingdian(String jingdian) {
		this.jingdian = jingdian;
	}
}

public class SearchShowBean {
	private String jingdian;
	private Drawable image;

	public Drawable getImage() {
		return image;
	}

	public void setImage(Drawable image) {
		this.image = image;
	}

	public String getJingdian() {
		return jingdian;
	}

	public void setJingdian(String jingdian) {
		this.jingdian = jingdian;
	}
}

以及数据建表的helper类:

public class HistoryHelper extends SQLiteOpenHelper {

	private static final int DB_VERSION = 1;

	public HistoryHelper(Context context) {
		super(context, Contance.DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(Contance.CREAT_HISTORY);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}

大致就是这些,下面是原码


项目原码





相关文章推荐

Android自定义工具栏(二)——试试Toolbar

接上篇,上篇提到要实现下面这个样子的工具栏: 主要是两个改动:一是把三个小圆点换成三个小方点,还有就是把弹出菜单的位置改到下面。 既然需要用到Toolbar这个组件,首先先在layout里加上下面这段...

Android获取验证码后倒计时程序

在开发是经常会遇到获取短信验证码,然后获取验证码后需要等待1分钟倒计时,这是是不能再次发送短信请求的,这是需要一个倒计时程序 这里我封装了一个Util类,希望对开发的小伙伴能有帮助,   pub...

历史纪录清除器

  • 2006年03月16日 00:00
  • 38KB
  • 下载

linux 下面清除历史纪录的方法

在linux下面,很多一般密码都是不显示的,但是有些时候,无意中我们就在明文中输入了我们需要执行的明文密码,这虽然不算什么,但是当服务器有另一个人管理的时候,并且你又不希望对方知道你管理的数据库,或者...

openfire 聊天历史纪录插件1

  • 2017年08月14日 01:29
  • 13KB
  • 下载

网吧救星历史纪录生成器

  • 2006年03月16日 00:00
  • 405KB
  • 下载

Matlab创建有价值历史纪录(完整版)

[转载〕 Matlab创建有价值历史纪录(完整版) % Matlab创建有价值历史纪录(完整版)% “%”为注释符% MATLAB% MATLAB是一种科学计算语言。它集成了计算,可视化和编程于一个易...

从SVN迁移到Git(包括SVN历史纪录)【最系统的讲解】

SVN to Git:从SVN迁移到Git教程,最全面的讲解git svn clone的各个参数,以及使用file:///协议的本地SVN服务器的迁移命令。...
  • cckit
  • cckit
  • 2015年09月21日 14:02
  • 832

续 Matlab创建有价值历史纪录(完整版)

 % ++++MATLAB矩阵示例% airfoil    %    美国太空总署机翼的稀疏矩阵的绘图示例。% buckydem    %    Buckminster Fuller的网格球顶连通图。...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:android搜索功能以及显示历史纪录带清除按钮
举报原因:
原因补充:

(最多只允许输入30个字)