I have a collapsed search EditView menu within my Actionbar (ActionbarSherlock). When setShowAsAction method is set to SHOW_AS_ACTION_NEVER, the keyboard displays and the user can start typing, as expected.
However when I set the value to SHOW_AS_ACTION_ALWAYS, the user has to touch the EditText before they start typing as it doesn’t appear to have focus!
Is there something wrong with my code or a way to work around this problem?
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
final MenuItem search = menu.add(0, MENU_SEARCH, MENU_SEARCH, getString(R.string.search));
search.setIcon(R.drawable.ic_action_search);
search.setActionView(R.layout.action_search);
search.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SEARCH:
mSearch = (EditText) item.getActionView();
mSearch.addTextChangedListener(mFilterTextWatcher);
mSearch.requestFocus();
mSearch.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}, 200);
break;
}
return true;
}
action_search.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint="@string/search" />
The solution was to nest the fragment within the Activity.