andro-girl
andro-girl

Reputation: 8129

searchview loases focus on orientation change

I am using searchview in my app with action bar and fragments. searchview is opened in the portrate mode and when we change the orientation it closes. If there is any text present in searchview it will not close on orientation chnage. I want to retain the state of searchview on orientation change even if the searchview is empty.How can i do this?i tried

 setRetainInstance(true);

But it is not working. Please help me.

Upvotes: 1

Views: 1566

Answers (2)

Frank
Frank

Reputation: 12300

I implemented it myself since Android does not seem to save it for me.

    final String s = savedSearchString;
    if (s != null) {
        searchViewMenuItem.expandActionView(); // opens the action view
    }

    searchView.post(new Runnable() {
        @Override
        public void run() {
            searchView.setQuery(s, false); // sets the last search string on the view
        } 
    });

'savedSearchString' is coming from the savedInstanceState. Make sure you set the initial conent of the search window on "" and not on null (default), otherwise it won't re-open an empty window.

Upvotes: 4

BSK-Team
BSK-Team

Reputation: 1810

You can create a boolean. And when you open the searchView, you put boolean to true. When you close the searchView, yout put boolean false.

In the onCreate, if the boolean = true, open the searchView.

final SearchView searchView = (SearchView) itemSearch.getActionView();
    searchView.setQueryHint(Html
            .fromHtml("<font color = #ffffff>Search...</font>"));

    searchView.setOnSearchClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //your code
        }
    });

Upvotes: 0

Related Questions