Android原生控件SearchView实现历史搜索记录

SearchView实现搜索记录看了一些大神写的贴子简单实现,

但我们功能 需要单独删除一条历史搜索记录,好像没在网上找到解决方案,原生方法上也只有suggestions.clearHistory(),历史纪录全部清除。后来看了一下 源码重写了SearchRecentSuggestionsProvider。

搜索实现下拉历史搜索记录

1、创建一个内容提供器:SearchRecentSugestionsprovider ,在AndroidManifest.xml中注册

class MySearchSuggestionsProvider : SearchRecentSuggestionsProvider() {
    init {
        setupSuggestions(AUTHORITY, MODE)
    }

    companion object {

        private val LOG_TAG = MySearchSuggestionsProvider::class.java.simpleName

        const val AUTHORITY = "cn.my.comment.MySearchSuggestionsProvider"
        const val MODE = SearchRecentSuggestionsProvider.DATABASE_MODE_QUERIES
    }
}


<provider
    android:authorities="cn.my.comment.MySearchSuggestionsProvider"
    android:name=".comment.MySearchSuggestionsProvider"></provider>

2、初始化资源文件

 fun initSearch4History(){

        mSuggestionAdapter = HistorySearchAdapter(this, R.layout.item_search_history_list, null)
        val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
        search.setSearchableInfo(searchManager.getSearchableInfo(componentName))
        search.suggestionsAdapter = mSuggestionAdapter
        suggestions = SearchRecentSuggestions(this,
                MySearchSuggestionsProvider.AUTHORITY, MySearchSuggestionsProvider.MODE)

        mSuggestionAdapter!!.setListener(object : OnHistoryDeleteClickListener {
            override fun onItemClick(query: String) {
                Toast.makeText(this@BaseActivity,"删除 ~~",Toast.LENGTH_SHORT).show()
                val deleteSuccess = deleteSuggestions(query)
                if(deleteSuccess == -1){
                    Toast.makeText(this@BaseActivity,"删除  失败",Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText(this@BaseActivity,"删除  成功   ",Toast.LENGTH_SHORT).show()
                }
            }

        })

    }
class HistorySearchAdapter(context: Context, resource: Int, cursor: Cursor?) : ResourceCursorAdapter(context, resource, cursor) {

    var onHistoryDeleteClickListener: OnHistoryDeleteClickListener? = null
    fun setListener(onHistoryDeleteClickListener:OnHistoryDeleteClickListener){
        this.onHistoryDeleteClickListener = onHistoryDeleteClickListener
    }

    override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup): View {
        val view = LayoutInflater.from(context).inflate(
                R.layout.item_search_history_list, parent, false)

        val viewHolder = ViewHolder(view)
        view.tag = viewHolder

        return view
    }

    override fun bindView(view: View, context: Context, cursor: Cursor) {
        val viewHolder = view.tag as ViewHolder
        val itemId: Int = cursor.getInt(cursor.getColumnIndex("_id"))
        val str = cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1))
        viewHolder.searchStr.text = str
        viewHolder.deleteBtn.setOnClickListener{
//            Toast.makeText(context,str,Toast.LENGTH_SHORT).show()
            if(onHistoryDeleteClickListener != null){
                onHistoryDeleteClickListener!!.onItemClick(itemId.toString())
                notifyDataSetChanged()
            }
        }
    }

    fun getSuggestionText(position: Int): String? {
        if (position >= 0 && position < cursor.count) {
            val cursor = cursor
            cursor.moveToPosition(position)
            return cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1))
        }
        return null
    }

    class ViewHolder(view: View) {
        var deleteBtn: ImageView = view.findViewById<View>(R.id.deleteBtn) as ImageView
        var searchStr: TextView = view.findViewById<View>(R.id.searchStr) as TextView

    }


}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="12dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:background="@color/white"
    >

    <ImageView
        android:id="@+id/deleteBtn"
        android:layout_width="@dimen/circle_header_size"
        android:layout_height="@dimen/circle_header_size"
        android:src="@mipmap/bx_emotion_delete"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        />

    <TextView
        android:id="@+id/searchStr"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:lines="1"
        android:ellipsize="end"
        tools:text="新西兰"
        android:layout_toLeftOf="@id/deleteBtn"
        android:layout_centerVertical="true"
        />



</RelativeLayout>

3、添加搜索事件

  search.setOnQueryTextListener(object : android.support.v7.widget.SearchView.OnQueryTextListener{

            override fun onQueryTextSubmit(query: String?): Boolean {
                // 先隐藏键盘
                closeInput(search)
                if(TextUtils.isEmpty(query)) return false
                searchStr = query!!

                //保存搜索关键词
                suggestions!!.saveRecentQuery(query, null)

                search()
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                //查找搜索历史
                val cursor = getRecentSuggestions(newText!!)
                mSuggestionAdapter!!.swapCursor(cursor)

                searchStr = newText.toString().trim()

                search()
                return true
            }

        }) 

 search.setOnSuggestionListener(object :android.support.v7.widget.SearchView.OnSuggestionListener{
            override fun onSuggestionSelect(position: Int): Boolean {
                return false
            }

            override fun onSuggestionClick(position: Int): Boolean {
                val str = mSuggestionAdapter!!.getSuggestionText(position)
                search.setQuery(str, true)
                searchStr = str!!
                search()
                return true
            }
        })


   /**
     * 搜索本地数据库,删除历史搜索记录
     */
    fun deleteSuggestions(id:String): Int? {
        val uriBuilder = Uri.Builder()
                .scheme(ContentResolver.SCHEME_CONTENT)
                .authority(MySearchSuggestionsProvider.AUTHORITY)

        uriBuilder.appendPath(SearchManager.SUGGEST_URI_PATH_QUERY)
        val uri = uriBuilder.build()
        return  contentResolver.delete(uri,"_id=$id",null)
    }

    /**
     * 搜索本地数据库,查找历史搜索记录
     */
    fun getRecentSuggestions(query: String): Cursor? {
        val uriBuilder = Uri.Builder()
                .scheme(ContentResolver.SCHEME_CONTENT)
                .authority(MySearchSuggestionsProvider.AUTHORITY)

        uriBuilder.appendPath(SearchManager.SUGGEST_URI_PATH_QUERY)

        val selection = " ?"
        val selArgs = arrayOf(query)

        val uri = uriBuilder.build()

        return contentResolver.query(uri, null, selection, selArgs, null)
    }

 

4、如果需要删除功能,需要重写MySearchSuggestionsProvider继承的SearchRecentSuggestionsProvider,修改delete方法如下

  /**
     * This method is provided for use by the ContentResolver.  Do not override, or directly
     * call from your own code.
     */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();

        final int length = uri.getPathSegments().size();
        if (length != 1) {
//            throw new IllegalArgumentException("Unknown Uri");
            System.out.println("-------------搜索历史纪录删除  Unknown Uri");
        }

        int count = 0;
        if (mUriMatcher.match(uri) == URI_MATCH_SUGGEST){
            count = db.delete(sSuggestions, selection, selectionArgs);
        } else {
//            throw new IllegalArgumentException("Unknown Uri");
            System.out.println("-------------搜索历史纪录删除  Unknown Uri");
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值