android實現搜尋功能並將搜尋結果儲存到SQLite中(例項程式碼)
阿新 • • 發佈:2020-04-23
執行結果:
涉及要點:
- ListView+EditText+ScrollView實現搜尋效果顯示
- 監聽軟鍵盤迴車執行搜尋
- 使用TextWatcher( )實時篩選
- 將搜尋內容儲存到SQLite中(可清空歷史記錄)
- 監聽EditText的焦點,獲得焦點彈出軟鍵盤同時顯示搜尋歷史,失去焦點隱藏軟體盤和ListView。
實現過程比較簡單,都是常用的,這裡就不講解了。程式碼可直接複製使用。
實現過程:
MainActivity.java
public class MainActivity extends Activity { private EditText et_search; private TextView tv_tip; private MyListView listView; private TextView tv_clear; ScrollView scrollView; private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this); private SQLiteDatabase db; private BaseAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); // 初始化控制元件 // 清空搜尋歷史 tv_clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteData(); queryData(""); } }); et_search.setOnKeyListener(new View.OnKeyListener() {// 輸入完後按鍵盤上的搜尋鍵 public boolean onKey(View v,int keyCode,KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回車鍵功能 // 隱藏鍵盤 ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow( getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS); // 按完搜尋鍵後將當前查詢的關鍵字儲存起來,如果該關鍵字已經存在就不執行儲存 boolean hasData = hasData(et_search.getText().toString().trim()); if (!hasData) { insertData(et_search.getText().toString().trim()); queryData(""); } Toast.makeText(MainActivity.this,"點選軟鍵盤搜尋!",Toast.LENGTH_SHORT).show(); } return false; } }); et_search.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view,boolean b) { if (b) { //獲得 scrollView.setVisibility(View.VISIBLE); } else {//市區焦點 scrollView.setVisibility(View.GONE); } } }); // 搜尋框的文字變化實時監聽 et_search.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s,int start,int count,int after) { } @Override public void onTextChanged(CharSequence s,int before,int count) { } @Override public void afterTextChanged(Editable s) { if (s.toString().trim().length() == 0) { tv_tip.setText("搜尋歷史"); } else { tv_tip.setText("搜尋結果"); } String tempName = et_search.getText().toString(); // 根據tempName去模糊查詢資料庫中有沒有資料 queryData(tempName); } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent,View view,int position,long id) { TextView textView = (TextView) view.findViewById(android.R.id.text1); String name = textView.getText().toString(); et_search.setText(name); Toast.makeText(MainActivity.this,name,Toast.LENGTH_SHORT).show(); ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow( getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS); //隱藏軟鍵盤 et_search.clearFocus(); et_search.setText(""); } }); // 插入測試資料 Date date = new Date(); long time = date.getTime(); insertData("LY" + time); queryData(""); // 第一次進入查詢所有的歷史記錄 } /** * 插入資料 */ private void insertData(String tempName) { db = helper.getWritableDatabase(); db.execSQL("insert into records(name) values('" + tempName + "')"); db.close(); } /** * 模糊查詢資料 */ private void queryData(String tempName) { Cursor cursor = helper.getReadableDatabase().rawQuery( "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ",null); // 建立adapter介面卡物件 adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,new String[]{"name"},new int[]{android.R.id.text1},CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); // 設定介面卡 listView.setAdapter(adapter); adapter.notifyDataSetChanged(); } /** * 檢查資料庫中是否已經有該條記錄 */ private boolean hasData(String tempName) { Cursor cursor = helper.getReadableDatabase().rawQuery( "select id as _id,name from records where name =?",new String[]{tempName}); //判斷是否有下一個 return cursor.moveToNext(); } /** * 清空資料 */ private void deleteData() { db = helper.getWritableDatabase(); db.execSQL("delete from records"); db.close(); } private void initView() { et_search = (EditText) findViewById(R.id.et_search); scrollView = findViewById(R.id.showSearch); tv_tip = (TextView) findViewById(R.id.tv_tip); listView = (com.cwvs.microlife.MyListView) findViewById(R.id.listView); tv_clear = (TextView) findViewById(R.id.tv_clear); // 調整EditText左邊的搜尋按鈕的大小 Drawable drawable = getResources().getDrawable(R.drawable.search); drawable.setBounds(0,60,60);// 第一0是距左邊距離,第二0是距上邊距離,60分別是長寬 et_search.setCompoundDrawables(drawable,null,null);// 只放左邊 } }
RecordSQLiteOpenHelper.java
public class RecordSQLiteOpenHelper extends SQLiteOpenHelper { private static String name = "temp.db"; private static Integer version = 1; public RecordSQLiteOpenHelper(Context context) { super(context,version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))"); } @Override public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) { } }
MyListView.java
public class MyListView extends ListView { public MyListView(Context context) { super(context); } public MyListView(Context context,AttributeSet attrs) { super(context,attrs); } public MyListView(Context context,AttributeSet attrs,int defStyle) { super(context,attrs,defStyle); } @Override protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec,expandSpec); } }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="fill_parent" android:layout_height="50dp" android:background="#be9999" android:orientation="horizontal" android:paddingRight="16dp"> <ImageView android:layout_width="45dp" android:layout_height="45dp" android:layout_gravity="center_vertical" android:padding="10dp" android:src="@drawable/back" /> <EditText android:id="@+id/et_search" android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="264" android:background="@null" android:drawableLeft="@drawable/search" android:drawablePadding="8dp" android:gravity="start|center_vertical" android:hint="輸入查詢的關鍵字" android:imeOptions="actionSearch" android:singleLine="true" android:textColor="@android:color/white" android:textSize="16sp" /> </LinearLayout> <ScrollView android:id="@+id/showSearch" android:layout_width="wrap_content" android:layout_height="300dp" android:visibility="gone"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="20dp"> <TextView android:id="@+id/tv_tip" android:layout_width="match_parent" android:layout_height="50dp" android:gravity="left|center_vertical" android:text="搜尋歷史" /> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#EEEEEE" /> <liyue.edu.cn.ncst.app.MyListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#EEEEEE" /> <TextView android:id="@+id/tv_clear" android:layout_width="match_parent" android:layout_height="40dp" android:background="#F6F6F6" android:gravity="center" android:text="清除搜尋歷史" /> <View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginBottom="20dp" android:background="#EEEEEE" /> </LinearLayout> </ScrollView> </LinearLayout>
完整程式碼下載 demo
到此這篇關於android實現搜尋功能並將搜尋結果儲存到SQLite中(例項程式碼)的文章就介紹到這了,更多相關android 搜尋功能搜尋結果儲存sqlite內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!