Android软键盘的隐藏与显示

需求:怎么让自己手机上的键盘开启和关闭呢?如 搜索:一个输入框和一个执行搜索的按钮。当输入完毕,点击执行按钮时,默认情况下,软键盘是不会自动关闭的。这样对用户体验来说是不友好的。怎么改?比较简单:

这里将用到InputMethodManagerInputManager ,这是系统封装的类,其中就有方法来控制键盘的开关闭。

这里我直接拿出一个对键盘管理的单例模式,在以后开发中可以直接使用:

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
 * 类功能描述:软键盘管理界面</br>
 *
 * @author yuyahao
 * @version 1.0 </p> 修改时间:</br> 修改备注:</br>
 */
public class InputManager {
    private Context context;
    public static InputManager  inputManager;
    private InputMethodManager imm;
    public InputManager(Context context){
        this.context = context;
        // 得到InputMethodManager的实例
        imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        totleShowSoftInput();
    }
    public static InputManager getInstances(Context context){
        if(inputManager == null){
            inputManager = new InputManager(context);
        }
        return inputManager;
    }
    /**
     * 切换软键盘的显示与隐藏
     */
    public void totleShowSoftInput(){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }
    /**
     * 判断软键盘 弹出
     */
    public void showSoftInput(){
        if (!imm.isActive()) { //
            imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
        }
    }

    public void showItemInput(EditText tv){
        if (!imm.isActive()) {
            imm.showSoftInputFromInputMethod(tv.getWindowToken(), 0);
        }
    }
    /**
     *关闭软键盘
     *针对于 有一个EdtxtView
     * @param input_email
     */
    public void hideSoftInput(EditText  input_email){
        if (imm.isActive()) {
            // 关闭软键盘,开启方法相同,这个方法是切换开启与关闭状态的
            imm.hideSoftInputFromWindow(input_email.getWindowToken(), 0);
        }
    }
    /**
     * 针对于 有多个EdtxtView
     * 关闭所有的软键盘
     */
    public void hideALlSoftInput(){
        View view =   ((Activity) context).getWindow().peekDecorView();
        if (view != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值