Android打开关闭软键盘

Edittext在项目十分常见,当用到搜索功能时,进入搜索页面需要自动弹出软键盘,点击搜索,就要将软键盘关闭,这里就是我的软键盘工具类,实现的2个功能:

1.软键盘的打开与关闭
2.判断当前软键盘是否打开

import android.app.Activity;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.util.Timer;
import java.util.TimerTask;

public class KeybordUtil {
    /**
     * 自动弹软键盘
     *
     * @param context
     * @param et
     */
    public static void showSoftInput(final Context context, final EditText et) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        et.setFocusable(true);
                        et.setFocusableInTouchMode(true);
                        //请求获得焦点
                        et.requestFocus();
                        //调用系统输入法
                        InputMethodManager inputManager = (InputMethodManager) et
                                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputManager.showSoftInput(et, 0);
                    }
                });
            }
        }, 200);
    }

    /**
     * 自动关闭软键盘
     * @param activity
     */
    public static void closeKeybord(Activity activity) {
        InputMethodManager imm =  (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }

    /**
     * 打开关闭相互切换
     * @param activity
     */
    public static void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,167评论 25 709
  • 今天上午来到公司后。测试项目时发现好友页面的搜索好友功能。只可以弹出一次软键盘,当第一次手动关闭后,第二次死也弹不...
    鲁克巴克诗阅读 1,410评论 0 1
  • 这两天孩子们都返回校园了,我同事的孩子今年上初一,同事心里各种忐忑不安,找人解决孩子中午吃饭问题,想办法把孩子...
    格格巫2015阅读 214评论 0 0
  • 当男人爱上吃雪糕的女人时,实际上他并不会象女人般喜欢吃雪糕,他爱吃的是女人的豆腐,就如同老董和老狼在上下九逛...
    雁心阅读 333评论 0 0
  • 我今天喝了两杯星巴克,吃了两个大鸡肉,和一个蛋挞,这是我的极限了,可能接下来的话都是因为我吃饱了,撑的。 上面是我...
    璞予及茶阅读 350评论 0 0