Android: Prevent soft keyboard from closing in a chat window

Viewed 559

I'm making a chat app and would like to keep the soft keyboard open while the chat window is visible. The keyboard should not hide when the user taps any other control on the same page. My view hierarchy looks like this:

LinearLayout
   RecyclerView
   LinearLayout

The child linear layout has an EditText and a button to send a message. Once the page is shown, I'm requesting focus on the edit text and showing soft input with the SHOW_FORCED flag. The problem is when I tap on the RecyclerView or the send button and if the edit text has focus, then the keyboard will hide.

Is it possible to make sure the edit text never loses focus (thus preventing the keyboard from disappearing)? I was able to accomplish this with ease on iOS, but I'm having difficulty with Android.

3 Answers

if you want to get the focus of editText not to lose use this,it worked for me

    edit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(!edit.hasFocus()){
        edit.requestFocus();
    }
  }
});

Keep in mind I have not tried building this, since is complex. I'll try adding an example, if I get the time.

I guess you want to build something akin to whatsapp. The most promising way, in my opinion, is to set up a global touchListener in your root linearLayout, which consumes all touch events while making the children unfocusable, therefore allowing you to manually handle all the touch events. If you detect a sliding touch, scroll the recyclerview accordingly. If you detect a touch in the edittext area, set the focus & open the keyboard. That way the touches won't change the focus state, keeping the keyboard open. Keep in mind you'll probable have to handle all the other touch scenarios. Start by creating the listener & make everything but the first layout not focusable on touch, and then build your specific interactions.

What you can do is that when the EditText loses focus, focus it again and show the keyboard. But this is just the workaround. If you can share what you have done so far it would be easy.

editText.setOnFocusChangeListener( new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v,boolean hasFocus) {
        if(!editText.hasFocus()) {
            editText.requestFocus();
            editText.postDelayed(() -> showSoftKeyboard(editText.getContext(),editText),100);
        }
    }
});

public static void showSoftKeyboard(Context context, View view) {
    InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
} 

The delay is because sometimes focus keyboard doesnt show up.

Related