SearchView's OnCloseListener doesn't work

前端 未结 18 2549
有刺的猬
有刺的猬 2020-11-27 02:44

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:

18条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 03:19

    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.

提交回复
热议问题