Android软键盘之代码改变软键盘状态

本文介绍了一个用于Android应用程序中软键盘管理的工具类,包括显示、隐藏及切换软键盘状态的方法。该工具类依赖于InputMethodManager服务,适用于需要精确控制软键盘显示情况的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android中软键盘的管理主要是通过InputMethodManager来完成的,

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

使用方法:

import android.app.Activity;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by Administrator on 2017/4/4.
 * 软键盘工具类
 */

public class KeyboardUtil {

    /**
     * 显示软键盘,当布局加载完成后调用,否则无效
     * @param context
     * @param focusView:必须为EditText或者其子类并且获得焦点,并且是VISIBLE
     */
    public static void showSoftInput(Context context, EditText focusView){
        InputMethodManager inputMethodManager= (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            focusView.requestFocus();
            inputMethodManager.showSoftInput(focusView,0);
        }
    }

    /**
     * 隐藏软键盘,当布局加载完成后调用,否则无效
     * @param context
     */
    public static void hideSoftInput(Context context){
        InputMethodManager inputMethodManager= (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(((Activity)context).getWindow().getDecorView().getWindowToken(),0);
        }
    }

    /**
     * 切换软键盘状态(隐藏-显示或显示-隐藏),当布局加载完成后调用,否则无效
     * @param context
     */
    public static void toggleSoftInput(Context context){
        InputMethodManager inputMethodManager= (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.toggleSoftInput(0,0);
        }
    }
}

参考博客: Android手动显示和隐藏软键盘

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值