Note: MY question is not about losing focus, it's about gaining focus, hence it is not a duplicate of the marked question
I have a search menuItem on my toolbar which, on click will open up a search layout ontop of it and allow user to search. I have tried the following solutions mentioned elsewhere in Stack Overflow but none of them seems to work. (I should mention that due to it being used elsewhere I can't edit the XML)
from here
searchText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(_searchText, InputMethodManager.SHOW_IMPLICIT);
This just pops up the keyboard, nothing happens I have tried this +
editText.setCursorVisible(true);
With various combinations of
setFocusable(true)
andsetFocusableInTouchMode(true);
before the aformentionedsearchText.setFocusable(true); searchText.setFocusableInTouchMode(true); searchText.requestFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(_searchText, InputMethodManager.SHOW_IMPLICIT);
Doing (1) in separate thread (using
Handler.post
)Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { editText.requestFocus(); InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT); } },100);
Calling
editText.performClick()
Clearing previous focus like so:
private void clearFocus() { if (activity.getCurrentFocus() != null) { InputMethodManager imm = (InputMethodManager) activity.getApplication().getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); activity.getCurrentFocus().clearFocus(); } }
My code sample:
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.action_search) {
menuItem.setVisible(false);
onClickForSearchMenuItem();
return true;
}
return super.onOptionsItemSelected(menuItem);
}
private void onClickForSearchMenuItem() {
if (searchLayoutInToolbar != null) {
searchLayoutInToolbar.setVisibility(View.VISIBLE);
final EditText editText = (EditText) searchLayoutInToolbar.findViewById(R.id.custom_Search_Layout_Search_EditText);
//clearFocus();
//editText.setFocusableInTouchMode(true);
//editText.setFocusable(true);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
activity.invalidateOptionsMenu();
}
}
The developer pages at android point out that
A View will not take focus if one of its parents has getDescendantFocusability() equal to FOCUS_BLOCK_DESCENDANTS
but none of the parents of my view are set to that