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

当我的活动显示时,我的EditText是集中的,但键盘不显示,我需要再次单击它来显示键盘(它应该显示时,我的活动显示)。 当我在键盘上点击完成时,键盘被解散,但EditText保持集中,我不想(因为我的编辑已经完成)。

继续说,我的问题是有一些更像iPhone的东西:保持键盘与我的EditText状态同步(聚焦/不聚焦),当然,如果有物理键盘,也不会呈现软键盘。


当前回答

我做了这个帮助课。 只需要传递context和你想要聚焦的View show keyboard和hide keyboard。 我希望这能有所帮助。

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);
}

}

其他回答

final InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

信不信由你,当我发现活动动画可以禁用软键盘时,我的软键盘问题得到了解决。当你用

i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

and

overridePendingTransition(0, 0);

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

对于Kotlin,只需使用以下扩展:

fun EditText.showKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun EditText.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

舱单内:

android:windowSoftInputMode="stateAlwaysVisible" -初始启动键盘。 android:windowSoftInputMode="stateAlwaysHidden" -初始隐藏键盘。

我也喜欢使用“adjustPan”,因为当键盘启动时,屏幕会自动调整。

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

我在使用视图动画时也遇到了类似的问题。所以我已经放了一个动画监听器,以确保在尝试请求对所显示的编辑文本进行键盘访问之前,我将等待动画结束。

    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) {
        }
    });