Android show softkeyboard with showSoftInput is not working?

后端 未结 12 2169
抹茶落季
抹茶落季 2020-12-28 13:49

I have created a trivial application to test the following functionality. When my activity launches, it needs to be launched with the softkeyboard open.

My code doe

12条回答
  •  梦谈多话
    2020-12-28 14:10

    Here is the modified version of Siddharth Garg's answer. It work's 100% of the time.

    import android.content.Context;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Looper;
    import android.util.Log;
    import android.view.View;
    import android.view.inputmethod.InputMethodManager;
    
    public class SoftInputService implements Runnable {
    
        private static final String TAG = SoftInputService.class.getSimpleName();
    
        private static final int INTERVAL_MS = 100;
    
        private Context context;
        private View targetView;
        private Handler handler;
    
        public SoftInputService(Context context, View targetView) {
            this.context = context;
            this.targetView = targetView;
            handler = new Handler(Looper.getMainLooper());
        }
    
        @Override
        public void run() {
            if (context == null || targetView == null) {
                return;
            }
    
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    
            if (!targetView.isFocusable() || !targetView.isFocusableInTouchMode()) {
                Log.d(TAG,"focusable = " + targetView.isFocusable() + ", focusableInTouchMode = " + targetView.isFocusableInTouchMode());
                return;
    
            } else if (!targetView.requestFocus()) {
                Log.d(TAG,"Cannot focus on view");
                post();
    
            } else if (!imm.showSoftInput(targetView, InputMethodManager.SHOW_IMPLICIT)) {
                Log.d(TAG,"Unable to show keyboard");
                post();
            }
        }
    
        public void show() {
            handler.post(this);
        }
    
        public static void hide(Context context, IBinder windowToekn) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(windowToekn, 0);
        }
    
        protected void post() {
            handler.postDelayed(this, INTERVAL_MS);
        }
    }
    

    Usage:

    // To show the soft input
    new SoftInputService(context, theEditText).show();
    // To hide the soft input
    SoftInputService.hide(context, theEditText.getWindowToken());
    

提交回复
热议问题