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

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

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


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

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

为了移除EditText上的焦点,你需要一个虚拟视图来抓取焦点。


关闭它,你可以使用

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

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

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

键盘很快就出现了。

我也有同样的问题。editText可视性从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, 0f, 0f, 0));
        yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));                          
    }
}, 200);

它为我工作100ms的延迟,但失败没有任何延迟或只有1ms的延迟。

注释部分代码显示了另一种方法,它只适用于某些设备。我在OS版本2.2(模拟器)、2.2.1(真实设备)和1.6(模拟器)上进行了测试。

这种方法使我免去了很多痛苦。

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

i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

and

overridePendingTransition(0, 0);

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

要使键盘出现,请使用

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

这个方法比直接调用InputMethodManager更可靠。

要关闭它,使用

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

以下代码摘自谷歌的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);
        }
    }
}

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

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

android:windowSoftInputMode="stateAlwaysVisible" - manifest文件中的>。

edittext.requestFocus ();-代码为>。

这将打开软键盘上的编辑文本有请求焦点作为活动出现。

只要在manifest文件中添加android:windowSoftInputMode="stateHidden"…

我在各种不同的情况下都有同样的问题,我发现的解决方案在一些情况下工作,但在其他情况下不工作,所以这里是一个在我发现的大多数情况下工作的组合解决方案:

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

有时劳科德鲁格的答案并不管用。我是这样做的,经过了一些尝试和错误:

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

showSoftInput根本不为我工作。

我想我需要设置输入模式:(这里在manifest中的Activity组件中)

android:windowSoftInputMode="stateVisible" 

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

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

如果这对你不起作用,试着加入一个ScrollView——无论如何这是无害的。

你可以试着强迫软键盘出现,这对我来说是有效的:

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

上面给出的所有解决方案(OnFocusChangeListener中的InputMethodManager交互)。onFocusChange监听器附加到您的EditText工作良好,如果您在活动中有单个编辑。

在我的例子中,我有两个编辑。

 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(键盘隐藏)。最后,看不到键盘了。

一般解决方案应该有正确的语句在if“显示键盘,如果EditText文本有焦点”

在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;
  }
final InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

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

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

当其他方法都不起作用时,就强制显示它:

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

然后,如果你想关闭它,例如在onPause()中,你可以调用:

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 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);
        }
    });

的问候。

代码片段……

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

我把这里的所有东西结合起来,对我来说是有效的:

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();
    }
}
editText.post(new Runnable() {
    @Override
    public void run() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
});

使用Xamarin,这对我来说是一个片段:

using Android.Views.InputMethods;
using Android.Content;

...

if ( _txtSearch.RequestFocus() ) {
  var inputManager = (InputMethodManager) Activity.GetSystemService( Context.InputMethodService );
  inputManager.ShowSoftInput( _txtSearch, ShowFlags.Implicit );
}

舱单内:

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

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

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

隐藏键盘,使用这个:

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

显示键盘:

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

这对我很管用。你也可以尝试用这个来显示键盘:

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

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

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

我做了这个帮助课。 只需要传递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);
}

}

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

您还可以创建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;
    }
}

在onCrete() activity()方法的editText上调用requestFocus()方法,并在相同的editText上调用clearFocus()方法,当在键盘上单击完成。

这很疯狂,但确实有效

fun showKeyboard(view: View) {
    try {
        InputMethodManager::class.java.getMethod(
                "showSoftInputUnchecked",
                Int::class.javaPrimitiveType,
                ResultReceiver::class.java
        ).apply {
            isAccessible = true
            invoke(view.context.inputMethodManager, 0, null)
        }
    }
    catch (e: Exception) {
       e.printStackTrace()
    }
}

如果EditText是在回收器或ListView和/或这有禁用状态使用下面的代码。

public static void showKeyboardByFocus(final View view)
    {
        view.requestFocus();

        InputMethodManager keyboard = SystemMaster.getInputMethodManager();
        keyboard.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);

        Runnable re = new Runnable()
        {
            @Override
            public void run()
            {
                view.setEnabled(true);
                view.requestFocus();
            }
        };

        Handler h = new Handler(Looper.getMainLooper());
        h.postDelayed(re, 360);
    }

对于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)
}

我用定时器。键盘可以显示编辑文本聚焦。

    edittext = (EditText) findViewById(R.id.edittext );
    edittext.requestFocus();
    edittext.setFocusableInTouchMode(true);
    if (edittext.requestFocus()) {
        final Thread timer = new Thread() {
            public void run() {
                try{
                    sleep(500);
                    InputMethodManager imm =(InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE);
                    imm.showSoftInput(edittext, SHOW_IMPLICIT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        timer.start();

只需在EditText视图中添加这一行:

android:isScrollContainer="true"

和TADA -键盘开始自动显示!

我也有类似的问题,发现了这个简单而奇怪的解决方法。

正如user3392439在这里已经提到的,键盘在焦点上的出现与XML文件中滚动组件的出现有某种奇怪的联系。

即使在同一XML中存在另一个包含上述行的EditText视图,也会使键盘出现,无论当前关注的是哪个EditText。

如果您的XML文件中至少有一个包含滚动组件的可见视图-键盘将自动显示在焦点上。

如果没有滚动-然后你需要点击EditText使键盘出现。

Kotlin扩展显示键盘的焦点。

这是之前的回答的组合,要么太长,要么不完整。

这个扩展在消息队列上发布了一个可运行的消息,在请求聚焦后显示软键盘:

fun View.showSoftKeyboard() {
    post {
        if (this.requestFocus()) {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
        }
    }
}

在需要时从任何视图调用它:

editText.showSoftKeyboard()

根据这个答案,我使用了setSoftInputMode方法,并覆盖了DialogFragment中的这些方法:

@Override
public void onCancel(@NonNull DialogInterface dialog) {
    super.onCancel(dialog);
    requireDialog().getWindow().setSoftInputMode(InputMethodManager.HIDE_IMPLICIT_ONLY);
}

@Override
public void onStart() {
    super.onStart();
    requireDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}

@Override
public void onStop() {
    super.onStop();
    requireDialog().getWindow().setSoftInputMode(InputMethodManager.HIDE_IMPLICIT_ONLY);
}

我也用这些方法创建了我自己的DialogFragment子类,所以当你创建另一个对话框并从这个类继承时,你会自动显示软键盘,而不需要任何其他编辑。希望对别人有用。

使用以下代码强制显示键盘:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);

没有一个答案对我有用。这里有一个简单的方法。

searchEditText.setVisibility(View.VISIBLE);
                final Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        searchEditText.requestFocus();
                    }
                }, 400);

只是将requestFocus()方法延迟了400ms。

在添加了这些线条后,对我来说很有用。

globalSearchBarMainActivity.setEnabled(true);
globalSearchBarMainActivity.requestFocus();

因为我的自动完整文本视图方法被隐藏,即可见:消失

所以需要加上上面两行

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(globalSearchBarMainActivity, InputMethodManager.SHOW_IMPLICIT);

当我阅读官方文档时,我认为这是最好的答案,只是将视图传递给参数,如您的EditText,但showSoftKeyboard似乎不能在横向上工作

private fun showSoftKeyboard(view: View) {
    if (view.requestFocus()) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }
}

private fun closeSoftKeyboard(view: View) {
    if (view.requestFocus()) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}

在尝试了每个单独的答案后,键盘没有出现。我有几个小时来解决这个问题,所以希望将来有人不要浪费它。

对于我来说,这个问题不是编程问题,我是在模拟器上测试,手机有硬件键盘,所以默认情况下它不会显示软件键盘,要解决这个问题,你需要确保通过关闭硬件键盘或启用软键盘来显示模拟器中的软输入。

我们只在API-15和16上遇到过这种情况。 下面是如何做到这一点的屏幕截图

关于Geny Motion模拟器:

在Android Studio模拟器:

芬兰湾的科特林:

val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

fun showKeyboard() {
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
    }

fun hideKeyboard() {
        imm.hideSoftInputFromWindow(phoneNoInputTxt.windowToken, 0);
    }

那你想怎么叫就怎么叫!

以下是我从Square得到的一个更可靠的解决方案:

fun View.focusAndShowKeyboard() { /** * This is to be called when the window already has focus. */ fun View.showTheKeyboardNow() { if (isFocused) { post { // We still post the call, just in case we are being notified of the windows focus // but InputMethodManager didn't get properly setup yet. val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) } } } requestFocus() if (hasWindowFocus()) { // No need to wait for the window to get focus. showTheKeyboardNow() } else { // We need to wait until the window gets focus. viewTreeObserver.addOnWindowFocusChangeListener( object : ViewTreeObserver.OnWindowFocusChangeListener { override fun onWindowFocusChanged(hasFocus: Boolean) { // This notification will arrive just before the InputMethodManager gets set up. if (hasFocus) { this@focusAndShowKeyboard.showTheKeyboardNow() // It’s very important to remove this listener once we are done. viewTreeObserver.removeOnWindowFocusChangeListener(this) } } }) } }

代码从这里开始。

我使用这个扩展函数来显示Kotlin的键盘。

fun EditText.requestFocusWithKeyboard() {
    post {
        dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0))
        dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0))
        setSelection(length())
    }
}

你可以把它叫做:

editText.requestFocusWithKeyboard()

除了非常方便之外:

您不必担心在所有可能的情况下关闭它,例如当您使用InputMethodManager.SHOW_FORCED导航返回时。 除了请求焦点,它还设置选择(光标到文本末尾)。

view.requestFocus()可能由于不同的原因而不能工作。所以键盘不会显示。

如果视图是不可聚焦的,那么它实际上不会聚焦 (isFocusable返回false),或者由于其他原因无法聚焦 条件(不可聚焦的触摸模式(isFocusableInTouchMode),而 设备处于触摸模式、不可见、未启用或没有 大小)。

我使用了这个解决方案:

 @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
    EditText searchView = findViewById(R.id.searchView);
    
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            showSoftKeyboard(searchView);
        }
    }, 300);
}

public void showSoftKeyboard(View view) {
    if (view.requestFocus()) {
        InputMethodManager imm = (InputMethodManager)
                view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}

kotlin扩展使用下面。

fun EditText.toggle() {
   requestFocus()
   val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
   imm.showSoftInput(this, 0)
}

通过以下方式访问:

editText.toggle()