Android 如何捕获 SearchView 的清除按钮点击?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24794377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:46:30  来源:igfitidea点击:

How do I capture SearchView's clear button click?

androidsearchview

提问by asmgx

How can I capture the event of user click on clear SearchViewtext by clicking on the X button on the right

如何SearchView通过单击右侧的 X 按钮捕获用户单击明文的事件

I already captured onQueryTextChangeevent but, this is for any text change not for that X button

我已经捕获了onQueryTextChange事件,但是,这是针对任何文本更改而不是针对该 X 按钮

回答by Sitram

After trying a lot of combinations, I found how to capture the event behind the X button in SearchView

尝试了很多组合后,发现如何在SearchView中捕捉X按钮后面的事件

Below is a code snippet from onCreateOptionsMenufunction in one of my apps. mSearchMenuand mSearchVieware global variables. The X is actually an ImageView with ID search_close_btnand the text area is an EditText view with ID search_src_text

下面是onCreateOptionsMenu我的一个应用程序中函数的代码片段。mSearchMenu并且mSearchView是全局变量。X 实际上是一个带有 ID 的 ImageView,search_close_btn文本区域是一个带有 ID 的 EditText 视图search_src_text

@SuppressLint("NewApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.country_list_activity_actions, menu);
        mSearchMenu = menu.findItem(R.id.action_search);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Get the SearchView and set the searchable configuration
            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

            // Assumes current activity is the searchable activity
            mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            mSearchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default

            // Get the search close button image view
            ImageView closeButton = (ImageView)mSearchView.findViewById(R.id.search_close_btn);

            // Set on click listener
            closeButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    LoggerUtils.d(LOG, "Search close button clicked");
                    //Find EditText view
                    EditText et = (EditText) findViewById(R.id.search_src_text);

                    //Clear the text from EditText view
                    et.setText("");

                    //Clear query
                    mSearchView.setQuery("", false);
                    //Collapse the action view
                    mSearchView.onActionViewCollapsed();
                    //Collapse the search widget
                    mSearchMenu.collapseActionView();
                }
            });
        }

        // When using the support library, the setOnActionExpandListener() method is
        // static and accepts the MenuItem object as an argument
        mSearchMenu.setOnActionExpandListener(new OnActionExpandListener() {

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                //Nothing to do here
                LoggerUtils.d(LOG, "Search widget expand ");
                return true; // Return true to expand action view
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                LoggerUtils.d(LOG, "Search widget colapsed ");
                return true; // Return true to collapse action view
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

回答by spaceMonkey

you can just use the onCloseListener()

你可以只使用 onCloseListener()

sv= (SearchView) findViewById(R.id.searchView1);

sv.setOnCloseListener(new OnCloseListener() {
            @Override
            public boolean onClose() {
                Toast t = Toast.makeText(MainActivity.this, "close", Toast.LENGTH_SHORT);
                t.show();

                return false;
            }
        });

回答by Jhegs

I had problems trying to find the component by its ID but I found another way to search this component using the context of the same SearchView

我在尝试通过其 ID 查找组件时遇到问题,但我找到了另一种使用相同 SearchView 的上下文搜索该组件的方法

// Catch event on [x] button inside search view
int searchCloseButtonId = searchView.getContext().getResources()
                .getIdentifier("android:id/search_close_btn", null, null);
ImageView closeButton = (ImageView) this.searchView.findViewById(searchCloseButtonId);
// Set on click listener
closeButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       // Manage this event.
    }
});

回答by Rafael

I use this code to catch text query clearing, and perform my actions

我使用此代码来捕获文本查询清除,并执行我的操作

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search, menu);

        SearchView searchView = (SearchView) menu.findItem(R.id.search_button).getActionView();
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String cs) {
                if (TextUtils.isEmpty(cs)){
                    //Text is cleared, do your thing
                }
                return false;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                //text query submitted
            }
        };
        searchView.setOnQueryTextListener(textChangeListener);

        return true;
    }

回答by leon

If you use Appcompat library, instead of using

如果你使用 Appcompat 库,而不是使用

getResources().getIdentifier("android:id/search_close_btn", null, null);

you can do this:

你可以这样做:

MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
View closeButton = searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
                closeButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //handle click
                    }
                });

EDIT AUGUST 2019:

2019 年 8 月编辑:

If you use androidx: androidx.appcompat.R.id.search_close_btn

如果您使用 androidx: androidx.appcompat.R.id.search_close_btn

回答by VINAY DANARADDI

    ImageView closeButton = (ImageView) this.searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);

    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Manage this event.


        }
    });

Use R.id.search_go_btn for "Submit" Button

使用 R.id.search_go_btn 作为“提交”按钮

回答by Eduardo Viana

A kotlin answer:

科特林回答:

mySearchView.setOnCloseListener(object : SearchView.OnCloseListener {
            override fun onClose(): Boolean {
                // Do your stuff
                return false
            }
        })

回答by yanis labrak

The solution from Eduardodoesnt work for me. I found something else which is working for Kotlin. I found this solution thanks to SjoerdvGesteland it's answer.

Eduardo的解决方案对我不起作用。我发现了其他适用于 Kotlin 的东西。由于SjoerdvGestel和它的答案,我找到了这个解决方案。

// Get the close button on the searchView
val closeButtonId: Int = searching.context.resources.getIdentifier("android:id/search_close_btn", null, null)
val closeButton = searching.findViewById(closeButtonId) as ImageView

// On close collapse the searchView
closeButton.setOnClickListener {
    searching.onActionViewCollapsed()
    true
}