38

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);
Rahul
  • 1,667
  • 6
  • 21
  • 38

16 Answers16

57

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.

Jacek Milewski
  • 3,304
  • 1
  • 18
  • 17
  • 5
    I have the same problem and this didn't work for me. This issue is a common problem seemingly without a common solution. I tried several hacks suggested by others and nothing seems to work for my situation. – Chad Jan 05 '14 at 05:47
  • Surprised this doesn't have more upvotes. Have been looking through StackOverflow all day and this was the only one that set the EditText View to focusable upon my Activity loading. Now I just need to figure out how to have the keyboard not load unless the user clicks on it with this solution. – AdamHurwitz May 18 '16 at 01:54
  • 2
    Such a under-voted answer but a GEM! Worked like a charm! – sud007 Jul 05 '17 at 10:20
  • `android:focusableInTouchMode="true"` in xml did the trick for me – qki Nov 19 '20 at 09:03
20

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

saleh sereshki
  • 2,402
  • 3
  • 17
  • 18
12

Following saleh sereshki's answer and pauminku's comment, I'm using:

m_SearchEditText.post(new Runnable() {
            @Override
            public void run() {
                m_SearchEditText.requestFocus();
            }
        });

which in Kotlin is the equivalent to:

m_SearchEditText.post { m_SearchEditText.requestFocus() }
RobertoAllende
  • 8,744
  • 4
  • 30
  • 49
  • 1
    Worked to perfection, .post allows you to focus any view on the screen. Most other answers may have 'worked' from android giving focus In it's normal cascading fashion – Rowan Berry Nov 21 '19 at 03:23
9

In your manifest.xml write:

<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />

And call m_SearchEditText.requestfocus() in oncreate().
OR,
Try:

if(m_SearchEditText.requestFocus()) {
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
ridoy
  • 6,274
  • 2
  • 29
  • 60
8

The following works for me and should help:

EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
S.A.Norton Stanley
  • 1,833
  • 3
  • 23
  • 37
5

As an extension to this answer (I didn't add it as a comment because of reputation...).

If you want to reduce the delayed time to zero, use handler.post() instead. Full code:

final Handler handler = new Handler();
handler.post(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);
    }
});
Community
  • 1
  • 1
Matias Olocco
  • 509
  • 4
  • 9
  • @Matis Olocco what exactly is mLastNameET, is it of type of view object like EditText or is it your edittext from xml layout id? becuase this method only takes int , int in the parameter . \ – Khay May 03 '18 at 18:19
  • @Khay you should ask to the author of the original answer. If you read my answer, it is just an extension of it. I did not write is as a comment, because back then I did not have enough points. – Matias Olocco Jun 04 '18 at 13:56
5

Minimalist Kotlin extension version because we should pretend these sorts of obtuse calls into system services are not necessary:

fun EditText.requestKeyboardFocus() {
    val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
methodsignature
  • 4,152
  • 2
  • 20
  • 21
4

U need two xml attributes also to achieve this:

android:focusable="true"
android:focusableInTouchMode="true"

Add them to the EditText as well as the parent layouts(Any layout inside which these views are). By default these are false, so the focus is not given to the requested view.

Source: https://developer.android.com/reference/android/view/View.html#attr_android:focusable

After u show the EditText based on the checkbox selection, add the next and previous focus points dynamically in code.

Hope this helps.

vibhor_shri
  • 374
  • 2
  • 12
  • on API 19 I only had android:focusableInTouchMode="true" and but the keyboard didn't come up. Adding android:focusable="true" fixed it. – steven smith Nov 12 '19 at 00:34
3

to focus you can use this function

editText.requestFocus()

you can have two different problems with EditText. one is EditText will be focused but the keyboard is not going to open, so as other answers said, you have to open the keyboard manually. other problem is EditText not gonna focused at all means nothing happened.

for opening keyboard you can do this after requestFocus :

val manager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
manager?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)

if EditText not focused at all check for this properties. EditText has to be focusable, visible, enable, focusableInTouchMode. enable all of them before calling requestFocus.

this.isFocusable = true
this.isFocusableInTouchMode = true
this.visibility = View.VISIBLE
this.isEnabled = true

and at the end you can use this kotlin extention to do all of this for you :

fun EditText.focus() {
    this.isFocusable = true
    this.isFocusableInTouchMode = true
    this.visibility = View.VISIBLE
    this.isEnabled = true
    this.isCursorVisible = true
    this.post {
        (this.context as? Activity)?.runOnUiThread {
            this.requestFocus()
            val manager =
                this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
            manager?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        }
    }
}
codegames
  • 1,651
  • 18
  • 16
0

In my case none of the answers above worked (they don't work in Nox, for example). To set focus to EditText, you could trick it into thinking that the user actually clicked it.

So I use MotionEvent, like this:

// simulate a click, which consists of ACTION_DOWN and ACTION_UP
MotionEvent eventDown = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0);
editText.dispatchTouchEvent(eventDown);
eventDown.recycle();

MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis(), MotionEvent.ACTION_UP, 0, 0, 0);
editText.dispatchTouchEvent(eventUp);
eventUp.recycle();

// To be on the safe side, also use another method
editText.setFocusableInTouchMode(true);
editText.requestFocus();
editText.requestFocusFromTouch();
Lev Leontev
  • 2,538
  • 2
  • 19
  • 31
0

The above solutions will work if the EditText is enabled.

In my code, I have disabled the view at one point and trying to request focus later without enabling. If none of the above worked, enable the EditText and then proceed with the above solutions.

In my case it is like,

 etpalletId.isEnabled = true
 etpalletId.text!!.clear()
 etpalletId.requestFocus()
 etpalletId.isCursorVisible = true
GiridharaSPK
  • 496
  • 7
  • 17
0

I was combining some answers and found the following solution:

fun Fragment.focusEditText(editText: EditText) {
Timer("Timer", false).schedule(50) {
    requireActivity().runOnUiThread(java.lang.Runnable {
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        val manager =
            requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        manager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
    })
}

The timer delay makes sure that the focus request is working and the keyboard is opened manually because it did not work implicitely for me.

duesterdust
  • 87
  • 1
  • 7
0

For some special cases in my code I do this:

later {
    showKeyboard()
    titleEdit.requestFocus()
}

In normal code it should look like this:

view.post {
    (view.context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
        .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
            InputMethodManager.HIDE_IMPLICIT_ONLY)
    titleEdit.requestFocus()
}

Explanation: Looks like in some cases toggleSoftInput is the only way but somehow it steal focus and it works in some case just in code tun after things gets initialized so has to be post for later execution.

Renetik
  • 5,887
  • 1
  • 47
  • 66
0

Make sure that your view is focusable if not then set it to focusable:

yourView.setFocusable(true);
yourView.setFocusableInTouchMode(true);

After that set focus as follows:

yourView.requestFocus() 

If that doesn't work then use this:

yourView.post(new Runnable() {
@Override
public void run() {
    yourView.requestFocus();
}
});

This will work, the reason behind this is the whole UI isn't loaded in order to set the focus on a specific UI element. In this cases, the focus can be overwritten by the system that might ignore your explicit request. So if you request the focus using a background thread (yes, I’m meaning using Thread or Runnable class) it should do the trick.

For more info visit this link: https://medium.com/@saishaddai/til-requestfocus-not-working-22760b417cf9

Muhammad Saad Rafique
  • 3,158
  • 1
  • 13
  • 21
0

It's working for request focus when sometime request focus not working

fun EditText.focus(activity: Activity) {
this.isFocusable = true
this.isFocusableInTouchMode = true
this.visibility = View.VISIBLE
this.isEnabled = true
this.isCursorVisible = true
this.post {
    activity?.runOnUiThread {
        this.requestFocus()
        val manager =
            this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
        manager?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
    }
}
Sumit Ojha
  • 283
  • 2
  • 8
0

This code solved my problem. All you need is to write onFocusChange() of the editText with showSoftInput() inside in onCreate() like this:

private EditText editText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity_layout);

    editText = findViewById(R.id.editText);

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
            }
        }
    });
}

public void buttonClick(EditText editText) {
    editText.requestFocus();
}
ТЁМА
  • 1
  • 1