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>
相关推荐
IT观测2 分钟前
深度分析俩款主流移动统计工具Appvue和openinstall
android·java·数据库
用户338675581954 分钟前
Android 四种常用布局完全解析(附实战项目截图)
android
用户5087532168446 分钟前
Android 资源类型全解析:深入理解四种常用布局
android
XiaoLeisj19 分钟前
Android 文件存储实战:从应用私有目录读写到网络文件落盘与公共存储接入
android·java·网络·文件操作
恋猫de小郭25 分钟前
Android Studio Panda 2 ,支持 AI 用 Vibe Coding 创建项目
android·前端·flutter
zhouping@38 分钟前
[极客大挑战 2020]Greatphp
android·ide·web安全·android studio
毕设源码-邱学长41 分钟前
【开题答辩全过程】以 基于 Android的超市服务评价系统的设计与实现为例,包含答辩的问题和答案
android
子非鱼yy1 小时前
详解MySQL的MVCC:多版本并发控制核心原理与实战解析
android·adb
$Qw1 小时前
google firebase service account json
android·google
段娇娇2 小时前
Android jetpack ViewBinding(一)使用篇
android·android jetpack