Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText request focus not working

I have an EditText and a Button. On click of the button i want to open the EditText keyboard and at the same time request focus on the EditText, So that the user directly start typing in the keyboard and text appears in the EditText. But in my case when i click the button it open the keyboard, but it won't set focus on the EditText, because of which user has to click the EditText again to write on it. What is the issue. Any help or suggestion.

Code On click of button

m_SearchEditText.requestFocus(); InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInputFromWindow(m_SearchEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); 
like image 258
Rahul Avatar asked Jul 11 '13 06:07

Rahul


People also ask

What is focus in EditText?

If the return-value of the method is true, a toast is shown and the focus should get back on the EditText again. The focus should always get back on the EditText and the keyboard should show, until the return-value of the method is false.

How do I change focus to EditText in Android?

This solution works (no need to add android:focusable="true"\android:focusableInTouchMode="true"): final EditText userEditText = (EditText)findViewById(R. id.


2 Answers

ensure that the edittext is focusable in touch mode. You can do it two way.

In xml:

android:focusableInTouchMode="true" 

in Java:

view.setFocusableInTouchMode(true); 

Personally I don't trust the XML definition of this param. I always request focus by these two lines of code:

view.setFocusableInTouchMode(true); view.requestFocus(); 

The keyboard shoul appear on itself without the need to call InputMethodManager.

It works in most of the cases. Once it did not work for me because I have lost the reference to the object due to quite heavy processing - ensure that this is not your issue.

like image 163
Jacek Milewski Avatar answered Oct 13 '22 01:10

Jacek Milewski


In my case it worked by adding a handler after you clicked to button and focus set in another view the focus can get back to your needed view.

just put this in your code:

final Handler handler = new Handler();                 handler.postDelayed(new Runnable() {                     @Override                     public void run() {                         lastview.getEditText().clearFocus();                         m_SearchEditText.requestFocus();                         InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);                           mgr.showSoftInput(mLastNameET, InputMethodManager.SHOW_IMPLICIT);                      }                 }, 100); 

I hope it was helpful

like image 32
saleh sereshki Avatar answered Oct 13 '22 01:10

saleh sereshki