Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focusing SearchView so the soft keyboard appears?

Tags:

android

I have a project that targets api 11 and above, so no actionbarsherlock.

I'm starting an activity with a SearchView. I want to focus the SearchView immediately, and have the soft keyboard up (if there's no hardware keyboard). I've tried:

mSearchView.requestFocus();
mSearchView.requestFocusFromTouch();

which does in fact focus the searchview, but it doesn't show the keyboard. I've read through other posts saying it's worked. Other posts try to force the keyboard up using:

InputMethodManager imm = (InputMethodManager)getSystemService(
    Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(
    InputMethodManager.SHOW_FORCED, 
    InputMethodManager.HIDE_IMPLICIT_ONLY);

which will show the keyboard, but then it behaves strangely after I submit a search query - it hides itself, then pops up again, then hides itself finally.

Anyone have a correct way of getting this to work?

Thanks

-------- Edit ----------------

Here's how I'm setting it up:

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    ...     

    MenuItem searchItem = menu.findItem(R.id.action_search); 
    mSearchView = (SearchView) searchItem.getActionView();
    mSearchView.setIconifiedByDefault(false);

    if (!mDidThisOnce) {
        mSearchView.requestFocusFromTouch();
        InputMethodManager imm = ...;
        imm.toggleSoftInput(...);
        mDidThisOnce = true;
    }
}

------ Last Edit -----------

So this works, but I needed to keep a flag to make sure I didn't run the imm code more than once, otherwise it keeps popping the keyboard up after you submit a search.

like image 455
user291701 Avatar asked Nov 12 '22 22:11

user291701


1 Answers

I had the same problem.

I have used searchView.clearFocus(); before and that worked for me.

like image 161
John Huang Avatar answered Nov 15 '22 01:11

John Huang