Android开发之实现搜索框搜索
最近自己在尝试做app开发,遇到搜索框功能,便查找了一下但是感觉自己想的或许更好理解和记住,便自己思考了一下。废话不多说,下面是实现代码,供大家参考,有待改进。
先说一下我整体思路,因为刚开始写所以相关数据都没有上传服务器过。首先建立一个数据库,将可以搜索的相关内容存储到数据库的搜索表当中,然后在搜索框中获取输入的第一个字符,按照字符搜索相关内容。同时创建历史搜索表,将搜索过的内容放入到搜索历史表当中去。每一次进入搜索页面都从搜索历史表当中获取之前的搜索历史,点击清空搜索历史将删除表中的所有内容。
这是我点击跳转到搜索界面,只需要关注最顶上即可
其中第一步就是自定listview布局,这一块一搬自定义的大多数相同
package com.example.tjtcexample.subsidiary.services1.search;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class ListViewForScrollView extends ListView {
public ListViewForScrollView(Context context) {
super(context);
}
public ListViewForScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListViewForScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expected=MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expected);
}
}
然后在xml中建立布局,效果见上图
android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_margin="10dp"> android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="1" android:background="@drawable/back" android:layout_gravity="center" android:id="@+id/iv_searchback"/> android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="8" android:orientation="horizontal" android:background="@drawable/search_round" android:id="@+id/linear_searchitem"> android:id="@+id/et_searchtext" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="3" android:hint="输入关键字搜索" android:background="@null" android:textSize="18sp" android:drawableLeft="@android:drawable/ic_menu_search" android:singleLine="true" android:imeOptions="actionSearch" /> android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/search_listview"/> android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp"> android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> android:layout_width="match_parent" android:layout_height="45dp" android:text="搜索历史" android:textSize="18sp" android:layout_gravity="center" android:gravity="center"/> android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tv_searchhistory" android:background="@color/teal_200"/> android:layout_width="match_parent" android:layout_height="2dp" android:background="@color/gray"/> android:id="@+id/tv_clearsearch" android:layout_width="match_parent" android:layout_height="45dp" android:text="清空搜索历史" android:textSize="18sp" android:layout_gravity="center" android:gravity="center"/>
public class SearchActivity extends AppCompatActivity {
private ImageView iv_searchBack;
private Button btn_search;
private EditText et_searchText;
private ListViewForScrollView listViewForScrollView;
private TextView tv_historyText,tv_clearHistory;
private List
private int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
initView();
setListeners();
}
/**
* 获取相对应的控件
*/
private void initView() {
iv_searchBack=findViewById(R.id.iv_searchback);
btn_search=findViewById(R.id.btn_search);
et_searchText=findViewById(R.id.et_searchtext);
listViewForScrollView=findViewById(R.id.search_listview);
tv_historyText=findViewById(R.id.tv_searchhistory);
tv_clearHistory=findViewById(R.id.tv_clearsearch);
}
/**
* 实现搜索功能
*/
private void setListeners() {
/**
* 存放搜索历史的表
*/
SQLiteOpenHelper helper=SearchSQLiteOpenHelper.getmInstance(SearchActivity.this);
/**
* 返回服务页面
*/
iv_searchBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(SearchActivity.this, Services1Activity.class);
startActivity(intent);
}
});
/**
* 给搜索历史传入空
*/
tv_historyText.setText(" ");
/**
* 搜索按钮的监听
*/
btn_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String obtain=et_searchText.getText().toString().trim();
/**
* 下一次点击搜索按钮时清空前一次搜索列表
*/
count++;
if(count%1==0){
searchList.clear();
}
/**
* 将搜索框内容放入到搜索历史当中去
*/
tv_historyText.append(obtain+" ");
/**
* 将搜索框内容放入到搜索历史表当中去
*/
SQLiteDatabase db_history=helper.getWritableDatabase();
if(db_history.isOpen()){
String add_historysearchname_sql="insert into historysearch(historyname) values(?);";
db_history.execSQL(add_historysearchname_sql,new Object[]{obtain});
Toast.makeText(SearchActivity.this,"增加成功",Toast.LENGTH_SHORT).show();
}
db_history.close();
/**
* 判断搜索框是否为空
*/
if(obtain.isEmpty()){
Toast.makeText(SearchActivity.this,"搜索框为空",Toast.LENGTH_SHORT).show();
searchList.clear();
}else{
/**
* 获取数据库中的表,取出搜索框中的首字符放入查询语句进行查询相匹配的内容
*/
SQLiteDatabase db_search=helper.getReadableDatabase();
if(db_search.isOpen()){
String firstChar=obtain.substring(0,1);
String query_sql="select * from search where searchname like '"+firstChar+"%'";
Cursor cursor = db_search.rawQuery(query_sql,null);
if(cursor.getCount()==0){
Toast.makeText(SearchActivity.this,"没有该服务",Toast.LENGTH_SHORT).show();
}else{
cursor.moveToFirst();
String searchname=cursor.getString(cursor.getColumnIndex("searchname"));
searchList.add(searchname);
}
while(cursor.moveToNext()){
String searchname1=cursor.getString(cursor.getColumnIndex("searchname"));
searchList.add(searchname1);
}
cursor.close();
}
db_search.close();
}
/**
* 自定义搜索适配器,将适配器放入自定义的listview当中
*/
SearchBaseAdapter searchBaseAdapter=new SearchBaseAdapter();
listViewForScrollView.setAdapter(searchBaseAdapter);
}
});
/**
* 搜索列表的点击事件
*/
listViewForScrollView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Toast.makeText(SearchActivity.this,"点击"+searchList.get(position),Toast.LENGTH_SHORT).show();
}
});
SQLiteDatabase db_get_history=helper.getReadableDatabase();
if(db_get_history.isOpen()){
String sql_history_query="select * from historysearch;";
Cursor cursor = db_get_history.rawQuery(sql_history_query, null);
if(cursor.getCount()==0){
Toast.makeText(SearchActivity.this,"没有搜索历史",Toast.LENGTH_SHORT).show();
}else{
cursor.moveToFirst();
String history_name=cursor.getString(cursor.getColumnIndex("historyname"));
tv_historyText.append(history_name+" ");
}
while (cursor.moveToNext()){
String history_name=cursor.getString(cursor.getColumnIndex("historyname"));
tv_historyText.append(history_name+" ");
}
cursor.close();
}
db_get_history.close();
tv_clearHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db_delete_history=helper.getWritableDatabase();
if(db_delete_history.isOpen()){
String sql_delete_history="delete from historysearch;";
db_delete_history.execSQL(sql_delete_history);
Toast.makeText(SearchActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
}
tv_historyText.setText(" ");
}
});
}
/**
* 适配器获取数据库中搜索表所存放的内容
*/
class SearchBaseAdapter extends BaseAdapter{
@Override
public int getCount() {
return searchList.size();
}
@Override
public Object getItem(int position) {
return searchList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
if(convertView==null){
convertView=View.inflate(SearchActivity.this,R.layout.searchlist_item,null);
holder=new ViewHolder();
holder.tv_searchLisItem=convertView.findViewById(R.id.tv_searchlistitem);
convertView.setTag(holder);
}else{
holder=(ViewHolder)convertView.getTag();
}
holder.tv_searchLisItem.setText(searchList.get(position));
return convertView;
}
}
class ViewHolder{
TextView tv_searchLisItem;
}
}
下面这就是建库建表的了
public class SearchSQLiteOpenHelper extends SQLiteOpenHelper {
private static SQLiteOpenHelper mInstance=null;
public static synchronized SQLiteOpenHelper getmInstance(Context context){
if(mInstance==null){
mInstance=new SearchSQLiteOpenHelper(context,"searchitem.db",null,3);
}
return mInstance;
}
public SearchSQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql="create table search(_id integer primary key autoincrement,searchname varchar(20));";
db.execSQL(sql);
String sql_history="create table historysearch(_id integer primary key autoincrement,historyname varchar(20));";
db.execSQL(sql_history);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
如果帮助到你,哈哈哈哈