SearchView 的 OnCloseListener 不起作用

发布于 2025-01-06 22:38:02 字数 1949 浏览 1 评论 0原文

我正在尝试在 Android 3.0+ ActionBar 中添加对 SearchView 的支持,但我无法让 OnCloseListener 工作。

这是我的代码:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    searchView = (SearchView) menu.findItem(R.id.search_textbox).getActionView();
    searchView.setOnQueryTextListener(new OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            searchLibrary(newText);
            return false;
        }
        @Override
        public boolean onQueryTextSubmit(String query) { return false; }
    });
    searchView.setOnCloseListener(new OnCloseListener() {
        @Override
        public boolean onClose() {
            System.out.println("Testing. 1, 2, 3...");
            return false;
        }
    });
    return true;
}

搜索效果很好,除了 OnCloseListener 之外,所有功能都正常。没有任何内容被打印到 Logcat。这是当我按下“关闭”按钮时的 Logcat:

02-17 13:01:52.914: I/TextType(446): TextType = 0x0
02-17 13:01:57.344: I/TextType(446): TextType = 0x0
02-17 13:02:02.944: I/TextType(446): TextType = 0x0

我查看了 文档 和示例,但似乎没有什么可以改变它。我在 Asus Transformer Prime 和 Galaxy Nexus 上运行它,两者都在 Ice Cream Sandwich 上。有什么想法吗?

更新:

是的 - System.out.println()确实有效。证据如下:

   @Override
 public boolean onQueryTextChange(String newText) {
    System.out.println(newText + "hello");
    searchLibrary(newText);
    return false;
 }

Logcat 中的结果:

02-17 13:04:20.094: I/System.out(21152): hello
02-17 13:04:24.914: I/System.out(21152): thello
02-17 13:04:25.394: I/System.out(21152): tehello
02-17 13:04:25.784: I/System.out(21152): teshello
02-17 13:04:26.064: I/System.out(21152): testhello

I'm trying to add support for the SearchView in the Android 3.0+ ActionBar, but I can't get the OnCloseListener to work.

Here's my code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    searchView = (SearchView) menu.findItem(R.id.search_textbox).getActionView();
    searchView.setOnQueryTextListener(new OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            searchLibrary(newText);
            return false;
        }
        @Override
        public boolean onQueryTextSubmit(String query) { return false; }
    });
    searchView.setOnCloseListener(new OnCloseListener() {
        @Override
        public boolean onClose() {
            System.out.println("Testing. 1, 2, 3...");
            return false;
        }
    });
    return true;
}

The search works great and every is working except for the OnCloseListener. Nothing is being printed to Logcat. Here's the Logcat for when I'm pressing the "Close" button:

02-17 13:01:52.914: I/TextType(446): TextType = 0x0
02-17 13:01:57.344: I/TextType(446): TextType = 0x0
02-17 13:02:02.944: I/TextType(446): TextType = 0x0

I've looked through the documentation and samples, but nothing seemed to change it. I'm running it on a Asus Transformer Prime and a Galaxy Nexus, both on Ice Cream Sandwich. Any ideas?

Update:

Yes - System.out.println() does work. Here's proof:

   @Override
 public boolean onQueryTextChange(String newText) {
    System.out.println(newText + "hello");
    searchLibrary(newText);
    return false;
 }

Results in this Logcat:

02-17 13:04:20.094: I/System.out(21152): hello
02-17 13:04:24.914: I/System.out(21152): thello
02-17 13:04:25.394: I/System.out(21152): tehello
02-17 13:04:25.784: I/System.out(21152): teshello
02-17 13:04:26.064: I/System.out(21152): testhello

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

云柯 2025-01-13 22:38:02

我也遇到这个问题,无奈只能放弃“oncloselistener”。相反,您可以获取 menuItem,然后获取 setOnActionExpandListener。然后重写未实现的方法。

@Override
public boolean onMenuItemActionExpand(MenuItem item) {
    // TODO Auto-generated method stub
    Log.d("*******","onMenuItemActionExpand");
    return true;
}

@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
    //do what you want to when close the sesarchview
    //remember to return true;
    Log.d("*******","onMenuItemActionCollapse");
    return true;
}

I also meet this problem, and I have no choice but give up "oncloselistener". Instead, you can get your menuItem, then setOnActionExpandListener. Then override unimplents methods.

@Override
public boolean onMenuItemActionExpand(MenuItem item) {
    // TODO Auto-generated method stub
    Log.d("*******","onMenuItemActionExpand");
    return true;
}

@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
    //do what you want to when close the sesarchview
    //remember to return true;
    Log.d("*******","onMenuItemActionCollapse");
    return true;
}
滥情哥ㄟ 2025-01-13 22:38:02

对于 Android API 14+(ICS 及更高版本),请使用以下代码:

// When using the support library, the setOnActionExpandListener() method is
// static and accepts the MenuItem object as an argument
MenuItemCompat.setOnActionExpandListener(menuItem, new OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {
        // Do something when collapsed
        return true;  // Return true to collapse action view
    }

    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {
        // Do something when expanded
        return true;  // Return true to expand action view
    }
});

有关更多信息:http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

参考:onActionCollapse/onActionExpand

For Android API 14+ (ICS and greater) use this code:

// When using the support library, the setOnActionExpandListener() method is
// static and accepts the MenuItem object as an argument
MenuItemCompat.setOnActionExpandListener(menuItem, new OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {
        // Do something when collapsed
        return true;  // Return true to collapse action view
    }

    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {
        // Do something when expanded
        return true;  // Return true to expand action view
    }
});

For more information: http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

Ref: onActionCollapse/onActionExpand

霞映澄塘 2025-01-13 22:38:02

对于这个问题我想出了这样的办法,

private SearchView mSearchView;

@TargetApi(14)
@Override
public boolean onCreateOptionsMenu(Menu menu)
{

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.conversation_index_activity_menu, menu);

    mSearchView = (SearchView) menu.findItem(R.id.itemSearch).getActionView();

    MenuItem menuItem = menu.findItem(R.id.itemSearch);

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    {
        menuItem.setOnActionExpandListener(new OnActionExpandListener()
        {

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item)
            {
                // Do something when collapsed
                Log.i(TAG, "onMenuItemActionCollapse " + item.getItemId());
                return true; // Return true to collapse action view
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item)
            {
                // TODO Auto-generated method stub
                Log.i(TAG, "onMenuItemActionExpand " + item.getItemId());
                return true;
            }
        });
    } else
    {
        // do something for phones running an SDK before froyo
        mSearchView.setOnCloseListener(new OnCloseListener()
        {

            @Override
            public boolean onClose()
            {
                Log.i(TAG, "mSearchView on close ");
                // TODO Auto-generated method stub
                return false;
            }
        });
    }


    return super.onCreateOptionsMenu(menu);

}

For this problem I came up with something like this,

private SearchView mSearchView;

@TargetApi(14)
@Override
public boolean onCreateOptionsMenu(Menu menu)
{

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.conversation_index_activity_menu, menu);

    mSearchView = (SearchView) menu.findItem(R.id.itemSearch).getActionView();

    MenuItem menuItem = menu.findItem(R.id.itemSearch);

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    {
        menuItem.setOnActionExpandListener(new OnActionExpandListener()
        {

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item)
            {
                // Do something when collapsed
                Log.i(TAG, "onMenuItemActionCollapse " + item.getItemId());
                return true; // Return true to collapse action view
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item)
            {
                // TODO Auto-generated method stub
                Log.i(TAG, "onMenuItemActionExpand " + item.getItemId());
                return true;
            }
        });
    } else
    {
        // do something for phones running an SDK before froyo
        mSearchView.setOnCloseListener(new OnCloseListener()
        {

            @Override
            public boolean onClose()
            {
                Log.i(TAG, "mSearchView on close ");
                // TODO Auto-generated method stub
                return false;
            }
        });
    }


    return super.onCreateOptionsMenu(menu);

}
断舍离 2025-01-13 22:38:02

我在 android 4.1.1 上遇到了同样的问题。看起来这是一个已知错误:https://code.google.com /p/android/issues/detail?id=25758

无论如何,作为一种解决方法,我使用了状态更改侦听器(当 SearchView 与操作栏分离时,它显然也被关闭)。

view.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {

    @Override
    public void onViewDetachedFromWindow(View arg0) {
        // search was detached/closed
    }

    @Override
    public void onViewAttachedToWindow(View arg0) {
        // search was opened
    }
});

上面的代码在我的例子中效果很好。


我在这里发布相同的答案:https://stackoverflow.com/a/24573266/2162924

I ran into same problem on android 4.1.1. Looks like it is a known bug: https://code.google.com/p/android/issues/detail?id=25758

Anyway, as a workaround i used state change listener (when SearchView is detached from action bar, it is also closed obviously).

view.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {

    @Override
    public void onViewDetachedFromWindow(View arg0) {
        // search was detached/closed
    }

    @Override
    public void onViewAttachedToWindow(View arg0) {
        // search was opened
    }
});

Above code worked well in my case.


I post same answer here: https://stackoverflow.com/a/24573266/2162924

阳光的暖冬 2025-01-13 22:38:02

我最终使用了一些 hack,这对我的目的来说很有效 - 不确定它是否适用于所有目的。不管怎样,我正在检查搜索查询是否为空。但这与 SearchViewOnCloseListener 并没有真正的关系 - 但这仍然不起作用!

searchView.setOnQueryTextListener(new OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.length() > 0) {
                    // Search
                } else {
                    // Do something when there's no input
                }
                return false;
            }
            @Override
            public boolean onQueryTextSubmit(String query) { return false; }
        });

I ended up using a bit of a hack, that works well for my purpose - not sure it'll work with all purposes. Anyway, I'm doing a check to see if the search query is empty. This is not really related to the SearchView's OnCloseListener though - that still doesn't work!

searchView.setOnQueryTextListener(new OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.length() > 0) {
                    // Search
                } else {
                    // Do something when there's no input
                }
                return false;
            }
            @Override
            public boolean onQueryTextSubmit(String query) { return false; }
        });
乞讨 2025-01-13 22:38:02

好吧,这解决了我的问题:

带有 showAsAction="always" 的菜单项

<item
    android:id="@+id/action_search"
    android:icon="@drawable/ic_action_search"
    android:title="Search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always"/>

并处于活动状态

searchView.setOnCloseListener(new OnCloseListener() {

        @Override
        public boolean onClose() {

            Log.i("SearchView:", "onClose");
            searchView.onActionViewCollapsed();
            return false;
        }
    });

Well, this solved my problem:

Menu item with showAsAction="always"

<item
    android:id="@+id/action_search"
    android:icon="@drawable/ic_action_search"
    android:title="Search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always"/>

and in activity

searchView.setOnCloseListener(new OnCloseListener() {

        @Override
        public boolean onClose() {

            Log.i("SearchView:", "onClose");
            searchView.onActionViewCollapsed();
            return false;
        }
    });
离去的眼神 2025-01-13 22:38:02

为了使 OnCloseListener 正常工作,请确保在搜索菜单项中将 showAsAction 设置为 always

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".SearchActivity">

    <item
        android:id="@+id/search"
        android:title="@string/search"
        android:icon="@drawable/ic_search_toolbar"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

In order to make the OnCloseListener work, make sure that showAsAction is set to always in the search menu item.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".SearchActivity">

    <item
        android:id="@+id/search"
        android:title="@string/search"
        android:icon="@drawable/ic_search_toolbar"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
酷遇一生 2025-01-13 22:38:02

创建菜单项,并将 app:showAsAction 设置为always。

<item   
 android:id="@+id/action_search"  
 android:title="..."  
 android:icon="..."  
 app:actionViewClass="android.support.v7.widget.SearchView"  
 app:showAsAction="always"/>

onCreateOptionsMenu 方法中创建 SearchView 时,执行类似的操作

inflater.inflate(R.menu.menu_search, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView search = (SearchView) item.getActionView();
search.setQueryHint(getString(R.string.search_brand_item));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
  @Override
  public boolean onQueryTextSubmit(String query) {
    // add your code
    return false;
  }

  @Override
  public boolean onQueryTextChange(String newText) {
    // add your code 
    return false;
  }
});
search.setOnCloseListener(new SearchView.OnCloseListener() {
  @Override
  public boolean onClose() {
    // add your code here
    return false;
  }
});
search.setIconifiedByDefault(true); // make sure to set this to true

search.setIconifiedByDefault(true) 需要设置为 true 调用上面创建的 SearchView.OnCloseListener() 上的 onClose() 方法。

Create the menu item with the app:showAsAction set to always.

<item   
 android:id="@+id/action_search"  
 android:title="..."  
 android:icon="..."  
 app:actionViewClass="android.support.v7.widget.SearchView"  
 app:showAsAction="always"/>

When creating the SearchView in the onCreateOptionsMenu method do something similar

inflater.inflate(R.menu.menu_search, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView search = (SearchView) item.getActionView();
search.setQueryHint(getString(R.string.search_brand_item));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
  @Override
  public boolean onQueryTextSubmit(String query) {
    // add your code
    return false;
  }

  @Override
  public boolean onQueryTextChange(String newText) {
    // add your code 
    return false;
  }
});
search.setOnCloseListener(new SearchView.OnCloseListener() {
  @Override
  public boolean onClose() {
    // add your code here
    return false;
  }
});
search.setIconifiedByDefault(true); // make sure to set this to true

The search.setIconifiedByDefault(true) needs to be set to true to call the onClose() method on the SearchView.OnCloseListener() created above.

电影里的梦 2025-01-13 22:38:02
    searchView.setOnCloseListener {
        d("click", "close clicked")
        return@setOnCloseListener false
    }

如果您点击关闭 searchView ->

D/单击:关闭单击

    searchView.setOnCloseListener {
        d("click", "close clicked")
        return@setOnCloseListener false
    }

if you click on close searchView ->

D/click: close clicked

一指流沙 2025-01-13 22:38:02

我遇到了同样的问题,onCloseListener 没有调用 SearchView。
25758中提出的错误问题以及我的一些帖子中了解已读过,要调用 onCloseListener,您需要设置:

searchView.setIconifiedByDefault(true);

但对于我的情况,我想打开搜索视图&并非一直图标化。我设法通过在下面添加一行来解决此问题:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_bar, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setOnQueryTextListener(queryTextListener);
    searchView.setIconifiedByDefault(true);
    searchView.setIconified(false);
    return true;
}

尽管在上一行中将默认值设置为 iconified,但 searchView.setIconified(false) 将导致 searchView 打开。通过这种方式,我设法拥有了 SearchView
一直打开&让它调用 onCloseListener。

I have encountered the same problem with onCloseListener not invoking for the SearchView.
Understand from the bug issue raised in 25758, and some postings I have read, to invoke onCloseListener, you need to set:

searchView.setIconifiedByDefault(true);

But for my case I wanted to have the search view opened & not iconified all the time. I manage to resolve this by adding one more line below:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_bar, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setOnQueryTextListener(queryTextListener);
    searchView.setIconifiedByDefault(true);
    searchView.setIconified(false);
    return true;
}

The searchView.setIconified(false) will cause the searchView to open up, despite setting the default to iconified to true in the previous line. In this way, I managed to have both a SearchView
that opens up all the time & having it invoke the onCloseListener.

落花浅忆 2025-01-13 22:38:02

对于 MenuItemCompat 问题,我添加了 ViewTreeObserver 来跟踪可见性状态。你可以在这里查看我的回答:
https://stackoverflow.com/a/28762632/1633609

For MenuItemCompat problem I added ViewTreeObserver to track the visibility state. You can check my answer here:
https://stackoverflow.com/a/28762632/1633609

小梨窩很甜 2025-01-13 22:38:02

我使用了 SearchView 关闭按钮并在其上设置了 setOnClickListener

searchView.findViewById<ImageView>(R.id.search_close_btn).setOnClickListener {
    searchView.setQuery("", false)
    searchView.clearFocus()
}

I used the SearchView close button and set a setOnClickListener on it

searchView.findViewById<ImageView>(R.id.search_close_btn).setOnClickListener {
    searchView.setQuery("", false)
    searchView.clearFocus()
}
往日 2025-01-13 22:38:02

未调用 OnCloseListener 的原因是 Android 代码中存在一个错误 - 仅当您还调用 setIconifiedByDefault(true) 时才会调用侦听器。

The reason the OnCloseListener is not called is because there is a bug in the Android code -- the listener is only called if you also call setIconifiedByDefault(true).

阿楠 2025-01-13 22:38:02

似乎已经是一个旧线程了,但我想我一开始就遇到了同样的问题 API 18。在谷歌搜索后,找到了这个线程,又花了一个小时阅读了javadoc,尝试并错误地发现了我在javadoc中没有假装完全理解的东西,现在对我来说以下工作:

searchView.setIconifiedByDefault(true);

   // OnQueryTextListener
   @Override
   public boolean onQueryTextSubmit(String query) {
      Log.d(tag, "onQueryTextSubmit: " + query);
      return true;
   }

   @Override
   public boolean onQueryTextChange(String query) {
      Log.d(tag, "onQueryTextChange: " + query);
      return true;
   }

   // OnCloseListener
   @Override
   public boolean onClose() {
      Log.w(tag, "onClose: ");
      return false;
   }

我玩了一下真/假,这在某种程度上产生了差异,现在它对我有用。希望它可以节省某人的时间。

seems an old thread already, but I thought I got the same problem API 18 in the first beginning. After googled around, found this thread, another hour read the javadoc tried and errored for something I don't pretend fully understand in javadoc, the following work for me now:

searchView.setIconifiedByDefault(true);

   // OnQueryTextListener
   @Override
   public boolean onQueryTextSubmit(String query) {
      Log.d(tag, "onQueryTextSubmit: " + query);
      return true;
   }

   @Override
   public boolean onQueryTextChange(String query) {
      Log.d(tag, "onQueryTextChange: " + query);
      return true;
   }

   // OnCloseListener
   @Override
   public boolean onClose() {
      Log.w(tag, "onClose: ");
      return false;
   }

I played with true/false a bit, that somehow makes the difference, and it works for me now. Hopefully, it could save someone time.

临走之时 2025-01-13 22:38:02

这是一种解决方法,但对我有用

  searchView.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {

                String lastText;

                @Override
                public boolean onQueryTextChange(final String newText) {
                    if (lastText != null && lastText.length() > 1 && newText.isEmpty()) {
                        // close ctn clicked

                        return true;
                    }
}

It's a workaround but has worked for me

  searchView.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {

                String lastText;

                @Override
                public boolean onQueryTextChange(final String newText) {
                    if (lastText != null && lastText.length() > 1 && newText.isEmpty()) {
                        // close ctn clicked

                        return true;
                    }
}
耳钉梦 2025-01-13 22:38:02

我在尝试检测 SearchView 的显示/关闭时遇到了这个问题。我最终使用了不同的监听器,它满足了我的需要:

        setOnQueryTextFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                // SearchView is being shown
            } else {
                // SearchView was dismissed
            }
        }

I encountered this issue while trying to detect the showing/dismissal of the SearchView. I ended up using a different listener and it worked for what I need:

        setOnQueryTextFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                // SearchView is being shown
            } else {
                // SearchView was dismissed
            }
        }
谈下烟灰 2025-01-13 22:38:02
searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
  @Override
  public void onViewAttachedToWindow(View v) {
    System.out.println("This is Fired When Search view was Expanded");
  }

  @Override
  public void onViewDetachedFromWindow(View v) {
    System.out.println("This is Fired When Search view was Closed");
  }
});
searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
  @Override
  public void onViewAttachedToWindow(View v) {
    System.out.println("This is Fired When Search view was Expanded");
  }

  @Override
  public void onViewDetachedFromWindow(View v) {
    System.out.println("This is Fired When Search view was Closed");
  }
});
审判长 2025-01-13 22:38:02

Android 中没有可登录的控制台。相反,使用 android 日志框架:

Log.d("Test Tag", "Testing.  1, 2, 3...");

另请参阅这个问题:为什么不' “System.out.println”在 Android 中工作吗?

There is no console in Android to log to. Instead, use the android logging framework:

Log.d("Test Tag", "Testing.  1, 2, 3...");

See also this question: Why doesn't "System.out.println" work in Android?

只有影子陪我不离不弃 2025-01-13 22:38:02

SearchView.setOnCloseListener() 有两种常见模式。这对所有听众来说都是如此,但我是在专门回答你的问题。第一种方法是创建侦听器函数并将其附加到成员变量,第二种方法是使类实现接口并将处理程序作为成员函数。

创建侦听器对象如下所示:

private SearchView mSearchView;
private final SearchView.OnCloseListener mOnCloseListener = 
    new SearchView.OnCloseListener() {
        public boolean onClose() {
            doStuff();
            return myBooleanResult;
        }
    };
mSearchView.setOnCloseListener(mOnCloseListener);

在类级别实现侦听器如下所示:

public class MyClass implements OnCloseListener {
    private SearchView mSearchView;

    public MyClass(...) {
        mSearchView.setOnCloseListener(this);
    }

    @Override
    public boolean onClose() {
        doStuff();
        return false;
    }
}

我没有看到任何创建 OnCloseListener ad-hoc 的示例,就像您在问题中所做的那样。

There are two common patterns for SearchView.setOnCloseListener(). This is really true of all listeners, but I'm addressing your question specifically. The first way is to create a listener function and attach it to a member variable, and the second is to make the class implement the interface and have the handler be a member function.

Creating a listener object looks like this:

private SearchView mSearchView;
private final SearchView.OnCloseListener mOnCloseListener = 
    new SearchView.OnCloseListener() {
        public boolean onClose() {
            doStuff();
            return myBooleanResult;
        }
    };
mSearchView.setOnCloseListener(mOnCloseListener);

Implementing listener at class level looks like this:

public class MyClass implements OnCloseListener {
    private SearchView mSearchView;

    public MyClass(...) {
        mSearchView.setOnCloseListener(this);
    }

    @Override
    public boolean onClose() {
        doStuff();
        return false;
    }
}

I have not seen any examples that create the OnCloseListener ad-hoc, as you did in your question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文