如何在单击其他活动时使SearchView失去焦点并崩溃 [英] How to make SearchView lose focus and collapse when clicking elsewhere on activity

查看:136
本文介绍了如何在单击其他活动时使SearchView失去焦点并崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我正在制作一个搜索界面,其中 SearchView 分别在丢失和获得焦点时折叠和展开。然而,失败的焦点只发生在两种情况下:

In my app, I'm making a search interface in which the SearchView collapses and expands when it loses and gains focus respectively. However, the losing focus thing is only happening in two cases:


  1. 按下后退按钮时。

  1. When the back button is pressed.

当按下 SearchView 旁边的主页图标时。

When the home icon beside the SearchView is pressed.

如果用户不仅点击这两件事,而且点击屏幕上的任何其他地方(例如,任何按钮或任何空白部分),我希望它失去焦点(并因此崩溃)没有视图的屏幕)。

I want it to lose focus (and hence collapse) if the user clicks not only on these two things, but anywhere else on the screen (e.g., any button or any blank portion of the screen without a view on it).

推荐答案

我发现了以下解决方案。我在每个不是searchview实例的视图上使用了setOnTouchListener来折叠搜索视图。它对我来说很完美。以下是代码。

Well I found out the following solution. I used setOnTouchListener on every view that is not an instance of searchview to collapse the searchview. It worked perfect for me. Following is the code.

public void setupUI(View view) {

    if(!(view instanceof SearchView)) {

        view.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                searchMenuItem.collapseActionView();
                return false;
            }

        });
    }

    //If a layout container, iterate over children and seed recursion.
    if (view instanceof ViewGroup) {

        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

            View innerView = ((ViewGroup) view).getChildAt(i);

            setupUI(innerView);
        }
    }
}

这是我提到的答案。

This is the answer I referred to.

这篇关于如何在单击其他活动时使SearchView失去焦点并崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆