Android如何自动弹出软键盘?

Android如何自动弹出软键盘?

  • 方法1
  • 方法2
    • [步骤1 添加windowSoftInputMode属性](#步骤1 添加windowSoftInputMode属性)
    • [步骤2 请求textinput焦点](#步骤2 请求textinput焦点)

方法1

直接在resume中控制弹出。不过需要一定的延时提交,因为需要保证当前的窗口是正在被服务的窗口。

java 复制代码
@Override
protected void onResume() {
    super.onResume();
    // 显示软键盘
    textInputEditText.postDelayed(() -> {
        textInputEditText.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(textInputEditText, InputMethodManager.SHOW_IMPLICIT);
        }
    }, 500);
}

显示不成功的log:

java 复制代码
Ignoring showSoftInput() as view=com.google.android.material.textfield.TextInputEditText{5ecc3f4 VFED..CL. .F...... 0,0-1074,146 #7f0801c0 app:id/textview aid=1073741824} is not served.

方法2

系统自动管理输入法显示

步骤1 添加windowSoftInputMode属性

  • stateVisible: 当页面打开时,如果有焦点的输入框,自动显示输入法。
  • adjustResize:键盘弹出时,Activity 内容会自动上移避免被遮挡。
xml 复制代码
<activity android:name=".SearchActivity"
    android:windowSoftInputMode="stateVisible|adjustResize"/>

步骤2 请求textinput焦点

这个可以放在onCreate或onResume都可以。

java 复制代码
 textInputEditText.requestFocus();

或:

加上

xml 复制代码
<com.google.android.material.textfield.TextInputEditText
    android:id="@+id/textview"

    android:layout_marginTop="30dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="hint" >
    <requestFocus />  
</com.google.android.material.textfield.TextInputEditText>
相关推荐
00后程序员张1 天前
iOS 上架费用全解析 开发者账号、App 审核、工具使用与开心上架(Appuploader)免 Mac 成本优化指南
android·macos·ios·小程序·uni-app·cocoa·iphone
来来走走1 天前
Android开发(Kotlin) 扩展函数和运算符重载
android·开发语言·kotlin
wuwu_q1 天前
用通俗易懂 + Android 开发实战的方式,详细讲解 Kotlin Flow 中的 retryWhen 操作符
android·开发语言·kotlin
天选之女wow1 天前
【代码随想录算法训练营——Day60】图论——94.城市间货物运输I、95.城市间货物运输II、96.城市间货物运输III
android·算法·图论
沐怡旸1 天前
【底层机制】Android对Linux线程调度的移动设备优化深度解析
android·面试
正经教主1 天前
【咨询】Android Studio 第三方手机模拟器对比【202511】
android·ide·android studio
Jomurphys1 天前
网络 - 缓存
android
似霰1 天前
安卓14移植以太网&&framework-connectivity-t 编译问题
android·framework·安卓·ethernet
Android-Flutter1 天前
kotlin - 显示HDR图(heic格式),使用GainMap算法,速度从5秒提升到0.6秒
android·kotlin