首页 文章

如何在关注edittext时显示软键盘

提问于
浏览
372

我想在 EditText 聚焦时自动显示软键盘(如果设备没有物理键盘),我有两个问题:

  • 当我显示 Activity 时,我的 EditText 已聚焦但键盘未显示,我需要再次单击它以显示键盘(显示我的 Activity 时应显示) .

  • 当我在键盘上单击完成时,键盘被解除但是 EditText 保持聚焦并且不想要(因为我的编辑完成了) .

要恢复,我的问题是在iPhone上有更多类似的东西:它使键盘与我的 EditText 状态保持同步(聚焦/不聚焦),当然如果有物理键盘,则不会出现软键盘 .

30 回答

  • 3

    showSoftInput 根本不适合我 .

    我想我需要设置输入模式:(此处在清单中的Activity组件中)

    android:windowSoftInputMode="stateVisible"
    
  • 68

    对于片段,确定它的工作:

    displayName = (EditText) view.findViewById(R.id.displayName);
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    
  • 3

    相信与否,当我发现活动动画可以禁用软键盘时,解决了我的软键盘问题 . 当你用the调用intent时

    i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    

    overridePendingTransition(0, 0);
    

    它可以隐藏软键盘,没有办法显示它 .

  • 5

    我将所有内容组合在一起,对我来说它有效:

    public static void showKeyboardWithFocus(View v, Activity a) {
        try {
            v.requestFocus();
            InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
            a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
  • 143

    要强制显示软键盘,您可以使用

    EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
    

    为了消除对 EditText 的关注,遗憾的是你需要一个虚拟 View 来 grab 焦点 .

    我希望这有帮助


    要关闭它你可以使用

    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
    

    这适用于在对话框中使用它

    public void showKeyboard(){
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }
    
    public void closeKeyboard(){
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }
    
  • 4

    我有同样的问题 . 在editText VISIBILITY从GONE更改为VISIBLE后,我不得不设置焦点并显示软键盘 . 我使用以下代码实现了这一点:

    new Handler().postDelayed(new Runnable() {
    
        public void run() {
    //        ((EditText) findViewById(R.id.et_find)).requestFocus();
    //              
            EditText yourEditText= (EditText) findViewById(R.id.et_find);
    //        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    //        imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
    
            yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
            yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));                           
        }
    }, 200);
    

    它适用于100毫秒延迟,但没有任何延迟或仅延迟1毫秒失败 .

    代码的注释部分显示了另一种方法,该方法仅适用于某些设备 . 我在OS 2.2版(仿真器),2.2.1(真实设备)和1.6(仿真器)上进行了测试 .

    这种方法给我带来了很多痛苦 .

  • 7

    要使键盘出现,请使用

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    

    此方法比直接调用InputMethodManager更可靠 .

    要关闭它,请使用

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    
  • 14

    以下代码是从Google 4.1的SearchView源代码中掠夺的 . 似乎工作,在较小版本的Android上也很好 .

    private Runnable mShowImeRunnable = new Runnable() {
        public void run() {
            InputMethodManager imm = (InputMethodManager) getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
    
            if (imm != null) {
                imm.showSoftInput(editText, 0);
            }
        }
    };
    
    private void setImeVisibility(final boolean visible) {
        if (visible) {
            post(mShowImeRunnable);
        } else {
            removeCallbacks(mShowImeRunnable);
            InputMethodManager imm = (InputMethodManager) getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
    
            if (imm != null) {
                imm.hideSoftInputFromWindow(getWindowToken(), 0);
            }
        }
    }
    

    然后,在创建Control / Activity时,需要添加以下代码 . (在我的例子中,它是一个复合控件,而不是一个活动) .

    this.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            setImeVisibility(hasFocus);
        }
    });
    
  • 2

    没有别的办法, force it to be shown

    editText.requestFocus();
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    
  • 2

    android:windowSoftInputMode="stateAlwaysVisible" - >在清单文件中 .

    edittext.requestFocus(); - >在代码中 .

    这将打开软键盘,当活动出现时,编辑文本会请求焦点 .

  • 8

    我在最近的一些简单案例中运用了下面的代码 . 我还没有完成所有测试,但....

    EditText input = (EditText) findViewById(R.id.Input);
    input.requestFocus();    
    input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
    input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
    

    然后键盘出现了 .

  • 61

    您可以尝试强制显示软键盘,它适用于我:

    ...
    dialog.show();
    input.requestFocus();
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    
  • 6

    要隐藏键盘,请使用以下键盘:

    getActivity().getWindow().setSoftInputMode(
        WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    

    并显示键盘:

    getActivity().getWindow().setSoftInputMode(
        WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    
  • 4

    有时raukodraug的答案是行不通的 . 我用这种方式做了一些试验和错误:

    public static void showKeyboard(Activity activity) {
        if (activity != null) {
            activity.getWindow()
                    .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
    
    public static void hideKeyboard(Activity activity) {
        if (activity != null) {
            activity.getWindow()
                    .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }
    }
    

    EditText 部分:

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(getActivity());
                } else {
                    showKeyboard(getActivity());
                }
            }
        });
    
  • 4

    我在各种不同的情况下遇到了同样的问题,我找到的解决方案在某些方面有效,但在其他方面不起作用,所以这里是一个联合解决方案,适用于我发现的大多数情况:

    public static void showVirtualKeyboard(Context context, final View view) {
        if (context != null) {
            final InputMethodManager imm =  (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            view.clearFocus();
    
            if(view.isShown()) {
                imm.showSoftInput(view, 0);
                view.requestFocus();
            } else {
                view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                    @Override
                    public void onViewAttachedToWindow(View v) {
                        view.post(new Runnable() {
                            @Override
                            public void run() {
                                view.requestFocus();
                                imm.showSoftInput(view, 0);
                            }
                        });
    
                        view.removeOnAttachStateChangeListener(this);
                    }
    
                    @Override
                    public void onViewDetachedFromWindow(View v) {
                        view.removeOnAttachStateChangeListener(this);
                    }
                });
            }
        }
    }
    
  • 0

    代码段 . . .

    public void hideKeyboard(Context activityContext){
    
        InputMethodManager imm = (InputMethodManager)
                activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    
        //android.R.id.content ( http://stackoverflow.com/a/12887919/2077479 )
        View rootView = ((Activity) activityContext)
                .findViewById(android.R.id.content).getRootView();
    
        imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0);
    }
    
    public void showKeyboard(Context activityContext, final EditText editText){
    
        final InputMethodManager imm = (InputMethodManager)
                activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    
        if (!editText.hasFocus()) {
            editText.requestFocus();
        }
    
        editText.post(new Runnable() {
            @Override
            public void run() {
                imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
            }
        });
    }
    
  • 1

    它对我有用 . 您也可以尝试使用它来显示键盘:

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    
  • 4

    只需在清单文件中添加android:windowSoftInputMode =“stateHidden”...

  • 2
    final InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
    keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
    
  • 0
    editText.post(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
        }
    });
    
  • 1

    上面给出的所有解决方案(如果您在活动中进行单个编辑,则附加到EditText的OnFocusChangeListener.onFocusChange侦听器中的InputMethodManager交互工作正常 .

    在我的情况下,我有两个编辑 .

    private EditText tvX, tvY;
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     tvX.setOnFocusChangeListener(this);
        tvY.setOnFocusChangeListener(this);
    
    @Override
    public void onFocusChange(View v, boolean hasFocus) {       
        InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(tvX.hasFocus() || tvY.hasFocus()) {            
            imm.showSoftInput(v, 0);            
        } else {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);         
        }       
    };
    

    我观察到onFocusChange是针对tvX触发的,其中hasFocus = true(显示键盘)但是后来针对tvY使用hasFocus = true(键盘隐藏) . 最后,没有键盘可见 .

    如果“如果EditText文本具有焦点显示键盘”,一般解决方案应该有正确的声明

  • 26

    在Activity的onResume()部分,你可以调用方法bringKeyboard();

    onResume() {
         EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
         bringKeyboard(yourEditText);
     }
    
    
      protected boolean bringKeyboard(EditText view) {
        if (view == null) {
            return false;
        }
        try {
          // Depending if edittext has some pre-filled values you can decide whether to bring up soft keyboard or not
            String value = view.getText().toString();
            if (value == null) {
                InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                return true;
            }
        } catch (Exception e) {
            Log.e(TAG, "decideFocus. Exception", e);
        }
        return false;
      }
    
  • 201

    在你的清单里面:

    android:windowSoftInputMode="stateAlwaysVisible" - 最初推出的键盘 . android:windowSoftInputMode="stateAlwaysHidden" - 最初隐藏的键盘 .

    我也喜欢使用 "adjustPan" 因为当键盘启动时屏幕会自动调整 .

    <activity
          android:name="YourActivity"
          android:windowSoftInputMode="stateAlwaysHidden|adjustPan"/>
    
  • 508

    我发现了一个奇怪的行为,因为在我的一个应用程序中,软键盘在进入活动时自动显示(onCreate中有一个editText.requestFocus()) .

    在进一步挖掘时,我发现这是因为布局周围有一个ScrollView . 如果我删除ScrollView,行为如原始问题陈述中所述:仅在单击已经聚焦的editText时才会显示软键盘 .

    如果它对您不起作用,请尝试放入ScrollView - 无论如何它都是无害的 .

  • 6

    我有 similar problem using view animations . 所以我在尝试在显示的edittext上请求键盘访问之前've put an animation listener to make sure I'd wait for the animation to end .

    bottomUp.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
    
            @Override
            public void onAnimationEnd(Animation animation) {
                if (textToFocus != null) {
                    // Position cursor at the end of the text
                    textToFocus.setSelection(textToFocus.getText().length());
                    // Show keyboard
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(textToFocus, InputMethodManager.SHOW_IMPLICIT);
                }
            }
    
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    
  • 0

    我同意raukodraug因此在swithview中你必须要求/明确焦点如下:

    final ViewSwitcher viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
        final View btn = viewSwitcher.findViewById(R.id.address_btn);
        final View title = viewSwitcher.findViewById(R.id.address_value);
    
        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewSwitcher.showPrevious();
                btn.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(btn, InputMethodManager.SHOW_IMPLICIT);
            }
        });
    
        // EditText affiche le titre evenement click
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btn.clearFocus();
                viewSwitcher.showNext();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(btn.getWindowToken(), 0);
                // Enregistre l'adresse.
                addAddress(view);
            }
        });
    

    问候 .

  • 28

    使用Xamarin,这对我在片段中起作用:

    using Android.Views.InputMethods;
    using Android.Content;
    
    ...
    
    if ( _txtSearch.RequestFocus() ) {
      var inputManager = (InputMethodManager) Activity.GetSystemService( Context.InputMethodService );
      inputManager.ShowSoftInput( _txtSearch, ShowFlags.Implicit );
    }
    
  • 1

    我做了这个帮助课程 . 只需传递上下文和要关注的视图,然后显示键盘,然后隐藏键盘 . 我希望它有帮助 .

    public class FocusKeyboardHelper {
    
    private View view;
    private Context context;
    private InputMethodManager imm;
    
    public FocusKeyboardHelper(Context context, View view){
        this.view = view;
        this.context = context;
        imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
    }
    
    public void focusAndShowKeyboard(){
    
        view.requestFocus();
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    
    }
    
    public void hideKeyBoard(){
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    

    }

  • 0
    void requestFocus(View editText, Activity activity)
    {
        try {
            editText.requestFocus();
            InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
    

    添加此行也不要忘记

    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    
  • 3

    您还可以创建EditText的自定义扩展,该扩展知道在获得焦点时打开软键盘 . 这就是我最终做的事情 . 这对我有用:

    public class WellBehavedEditText extends EditText {
        private InputMethodManager inputMethodManager;
        private boolean showKeyboard = false;
    
        public WellBehavedEditText(Context context) {
            super(context);
            this.initializeWellBehavedEditText(context);
        }
    
        public WellBehavedEditText(Context context, AttributeSet attributes) {
            super(context, attributes);
            this.initializeWellBehavedEditText(context);
        }
    
        public WellBehavedEditText(Context context, AttributeSet attributes, int defStyleAttr) {
            super(context, attributes, defStyleAttr);
            this.initializeWellBehavedEditText(context);
        }
    
        public WellBehavedEditText(Context context, AttributeSet attributes, int defStyleAttr, int defStyleRes) {
            super(context, attributes, defStyleAttr, defStyleRes);
            this.initializeWellBehavedEditText(context);
        }
    
        private void initializeWellBehavedEditText(Context context) {
            this.inputMethodManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
    
            final WellBehavedEditText editText = this;
            this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if(showKeyboard) {
                        showKeyboard = !(inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_FORCED));
                    }
                }
            });
        }
    
        @Override
        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
            if(!focused) this.showKeyboard = false;
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }
    
        @Override
        public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
            boolean result = super.requestFocus(direction, previouslyFocusedRect);
            this.showKeyboard = true;
            final WellBehavedEditText self = this;
            this.post(new Runnable() {
                @Override
                public void run() {
                    showKeyboard = !(inputMethodManager.showSoftInput(self, InputMethodManager.SHOW_FORCED));
                }
            });
            return result;
        }
    }
    

相关问题