键盘操作工具类KeyBoardUtils

时间:2019-10-31
本文章向大家介绍键盘操作工具类KeyBoardUtils,主要包括键盘操作工具类KeyBoardUtils使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

键盘操作工具类KeyBoardUtils


import android.annotation.SuppressLint;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class KeyboardUtils {
    public KeyboardUtils() {
    }

    public static void showKeyboard(Context context) {
        ((InputMethodManager)((InputMethodManager)context.getSystemService("input_method"))).toggleSoftInput(0, 1);
    }

    public static void showKeyboard(View view, Context context) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager)context.getSystemService("input_method");
        imm.showSoftInput(view, 1);
    }

    public static void toggleKeyboard(Context context) {
        ((InputMethodManager)((InputMethodManager)context.getSystemService("input_method"))).toggleSoftInput(1, 0);
    }

    public static void hideKeyboard(Context ctx, View view) {
        if (ctx != null && view != null) {
            view.clearFocus();
            InputMethodManager imm = (InputMethodManager)ctx.getSystemService("input_method");
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public static boolean isOpenInput(Context ctx, EditText etx) {
        InputMethodManager imm = (InputMethodManager)ctx.getSystemService("input_method");
        return imm.isActive(etx);
    }

    public static void registerActionHideInputListener(final Context context, final View view) {
        view.setOnTouchListener(new OnTouchListener() {
            @SuppressLint({"ClickableViewAccessibility"})
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == 0) {
                    KeyboardUtils.hideKeyboard(context, view);
                }

                return false;
            }
        });
    }
}

原文地址:https://www.cnblogs.com/Ricardoldc/p/11772136.html