Android如何使EditText获取焦点,并且将光标定位在文字尾部(包括键盘的弹出与收回)

代码:

   editText.setFocusable(true);
   editText.setFocusableInTouchMode(true);
   editText.requestFocus();
   editText.setSelection(editText.getText().length());

并弹出手机软键盘:

 getWindow().getDecorView().post(() -> {
       InputMethodManager inputManager =
       (InputMethodManager) this.getSystemService(
            Context.INPUT_METHOD_SERVICE);
       inputManager.showSoftInput(remarkEditText, 0);
        });

点击手机屏幕空白处,收起软键盘:

 //点击空白处 收起键盘
    private void initListener() {
        // mRootView为整个页面的view层
        mRootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              if (getCurrentFocus() != null){
               hideKeyboard(mRootView,getCurrentFocus().getWindowToken());
                }
            }
        });
    }
    private void hideKeyboard(final View view, IBinder windowToken) {
        if(windowToken == null){
            return;
        }
        InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager == null){
            return;
        }
        boolean active = inputMethodManager.isActive();
        if (active) {
            inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
        }
    }

你可能感兴趣的:(Android如何使EditText获取焦点,并且将光标定位在文字尾部(包括键盘的弹出与收回))