Android 弹出Dialog的时候如何弹出软键盘(输入法)

1、写一个软键盘管理类。

package com.phone.common_library.manager;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.phone.common_library.callback.OnSoftKeyBoardChangeListener;

import java.util.List;

/**
 * author    : Urasaki
 * e-mail    : 1164688204@qq.com
 * date      : 2020/3/11 9:23
 * introduce : 软键盘管理类
 */

public class SoftKeyboardManager {

    private static final String TAG = SoftKeyboardManager.class.getSimpleName();
    private View rootView;//activity的根视图
    private int rootViewVisibleHeight;//纪录根视图的显示高度
    private OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener;

    public SoftKeyboardManager(Activity activity) {
        //获取activity的根视图
        rootView = activity.getWindow().getDecorView();

        //监听视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //获取当前根视图在屏幕上显示的大小
                Rect r = new Rect();
                rootView.getWindowVisibleDisplayFrame(r);

                int visibleHeight = r.height();
                System.out.println(""+visibleHeight);
                if (rootViewVisibleHeight == 0) {
                    rootViewVisibleHeight = visibleHeight;
                    return;
                }

                //根视图显示高度没有变化,可以看作软键盘显示/隐藏状态没有改变
                if (rootViewVisibleHeight == visibleHeight) {
                    return;
                }

                //根视图显示高度变小超过200,可以看作软键盘显示了
                if (rootViewVisibleHeight - visibleHeight > 200) {
                    if (onSoftKeyBoardChangeListener != null) {
                        onSoftKeyBoardChangeListener.keyBoardShow(rootViewVisibleHeight - visibleHeight);
                    }
                    rootViewVisibleHeight = visibleHeight;
                    return;
                }

                //根视图显示高度变大超过200,可以看作软键盘隐藏了
                if (visibleHeight - rootViewVisibleHeight > 200) {
                    if (onSoftKeyBoardChangeListener != null) {
                        onSoftKeyBoardChangeListener.keyBoardHide(visibleHeight - rootViewVisibleHeight);
                    }
                    rootViewVisibleHeight = visibleHeight;
                    return;
                }

            }
        });
    }

    private void setOnSoftKeyBoardChangeListener(OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {
        this.onSoftKeyBoardChangeListener = onSoftKeyBoardChangeListener;
    }

    public static void setListener(Activity activity, OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {
        SoftKeyboardManager softKeyBoardListener = new SoftKeyboardManager(activity);
        softKeyBoardListener.setOnSoftKeyBoardChangeListener(onSoftKeyBoardChangeListener);
    }

    /**
     * 显示软键盘(输入法)(可用于Activity,Fragment)
     *
     * @param activity
     * @param editText
     */
    public static void showInputMethod(final Activity activity, final EditText editText) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }


    /**
     * 隐藏软键盘(输入法)(可用于Activity,Fragment)
     *
     * @param activity
     */
    public static void hideInputMethod(final Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive() && activity.getCurrentFocus() != null) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 显示软键盘(输入法)(只适用于Activity,不适用于Fragment)
     */
    public static void showSoftKeyboard2(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            if (inputMethodManager != null) {
                inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
            }
        }
    }

    /**
     * 隐藏软键盘(输入法)(只适用于Activity,不适用于Fragment)
     */
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            if (inputMethodManager != null) {
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 隐藏软键盘(输入法)(可用于Activity,Fragment)
     */
    public static void hideSoftKeyboard(Context context, List<View> viewList) {
        if (viewList == null) return;

        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);

        for (View v : viewList) {
            if (inputMethodManager != null) {
                inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

}

2、在弹出Dialog的时候弹出软键盘(这里是自定义的Dialog,普通的Dialog也是一样的)。


    /**
     * 注意:如果输入特殊小数或整数,如:.或.15或10.或00035或输入21153.67589,然后删除中间小数点,整数就是10位了(整数不能大于5位),
     * 则要在点击Dialog确认按钮之前进行提示,这样就不会填入不符合规范的整数或小数了。
     */
    private void showEditTextInputLimitsDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_layout_edit_text_input_limits, null, false);
        EditText edtInput = (EditText) view.findViewById(R.id.edt_input);
        TextView tevCancel = (TextView) view.findViewById(R.id.tev_cancel);
        TextView tevConfirm = (TextView) view.findViewById(R.id.tev_confirm);
        //小数点前边几位(修改这里可以自定义)
        int beforeDecimalNum = 5;
        //小数点后边几位(修改这里可以自定义)
        int afterDecimalNum = 5;
        //最大长度是多少位(修改这里可以自定义)
        int maxLength = 11;
        //输入的类型可以是整数或小数
        edtInput.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        DecimalInputFilter decimalInputFilter = new DecimalInputFilter(beforeDecimalNum, afterDecimalNum);
        //输入总长度多少位,小数几位(修改这里可以自定义)
        InputFilter[] inputFilter = {new InputFilter.LengthFilter(maxLength), decimalInputFilter};
        edtInput.setFilters(inputFilter);
        edtInput.addTextChangedListener(new DecimalTextWatcher(edtInput, afterDecimalNum));

        @SuppressLint("RestrictedApi")
        AlertDialog alertDialog = new AlertDialog.Builder(this, R.style.dialog_decimal_style)
                .setView(view, 0, 0, 0, 0)
                .show();

//        int widthPx = ScreenManager.getScreenWidth(this);
//        int widthDp = ScreenManager.pxToDp(this, widthPx);
//        int heightPx = ScreenManager.getScreenHeight(this);
//        int heightDp = ScreenManager.pxToDp(this, heightPx);
//        LogManager.i(TAG, "widthDp*****" + widthDp);
//        LogManager.i(TAG, "heightDp*****" + heightDp);

        tevCancel.setOnClickListener(v -> {
            SoftKeyboardManager.hideInputMethod(this);
            alertDialog.dismiss();
        });
        tevConfirm.setOnClickListener(v -> {
            String afterData = edtInput.getText().toString();
            if (!TextUtils.isEmpty(afterData)) {
                if (afterData.contains(".")) {
                    String[] afterDataArr = afterData.split("\\.");
                    if ("".equals(afterDataArr[0])) {
                        Toast.makeText(this, "请输入正常整数或小数", Toast.LENGTH_SHORT).show();
                    } else if (afterDataArr.length == 1) {//当afterData是这种类型的小数时(0. 100.)
                        Toast.makeText(this, "请输入正常整数或小数", Toast.LENGTH_SHORT).show();
                    } else {
                        this.tevShowInput.setText(edtInput.getText().toString());
                        SoftKeyboardManager.hideInputMethod(this);
                        alertDialog.dismiss();
                    }
                } else {
                    if (afterData.length() <= beforeDecimalNum) {
                        String[] afterDataArr = afterData.split("");
                        if (afterDataArr.length > 1 && "0".equals(afterDataArr[1])) {
                            Toast.makeText(this, "请输入正常整数或小数", Toast.LENGTH_SHORT).show();
                        } else {
                            this.tevShowInput.setText(edtInput.getText().toString());
                            SoftKeyboardManager.hideInputMethod(this);
                            alertDialog.dismiss();
                        }
                    } else {
                        Toast.makeText(this, "整数长度不能大于" + beforeDecimalNum + "位", Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(this, "请输入整数或小数", Toast.LENGTH_SHORT).show();
            }
        });


        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        edtInput.setFocusable(true);
        edtInput.setFocusableInTouchMode(true);
        edtInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    SoftKeyboardManager.showInputMethod(EditTextInputLimitsActivity.this, edtInput);
                } else {

                }
            }
        });
        edtInput.requestFocus();
    }

3、添加自定义Dialog的layout。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="@dimen/dp_300"
    android:layout_height="@dimen/dp_240"
    android:background="@drawable/corners_14_color_white"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="@dimen/dp_300"
        android:layout_height="@dimen/dp_240"
        android:orientation="vertical"
        tools:ignore="UselessParent">

        <View
            android:layout_width="match_parent"
            android:layout_height="@dimen/dp_20" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="@dimen/dp_40"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:paddingStart="@dimen/dp_10"
            android:paddingEnd="@dimen/dp_10"
            android:text="@string/decimal_en"
            android:textColor="@color/blue"
            android:textSize="@dimen/sp_16" />

        <View
            android:layout_width="match_parent"
            android:layout_height="@dimen/dp_20" />

        <EditText
            android:id="@+id/edt_input"
            android:layout_width="@dimen/dp_240"
            android:layout_height="@dimen/dp_40"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/corners_14_color_white_stroke_1_color_80000000"
            android:gravity="center_vertical"
            android:paddingStart="@dimen/dp_15"
            android:paddingEnd="@dimen/dp_15"
            android:textColor="@color/colorBlack333"
            android:textSize="@dimen/sp_16"
            tools:ignore="Autofill,LabelFor,TextFields" />

        <View
            android:layout_width="match_parent"
            android:layout_height="@dimen/dp_20" />

        <FrameLayout
            android:layout_width="@dimen/dp_200"
            android:layout_height="@dimen/dp_40"
            android:layout_gravity="center_horizontal">

            <TextView
                android:id="@+id/tev_cancel"
                android:layout_width="@dimen/dp_80"
                android:layout_height="@dimen/dp_40"
                android:layout_gravity="start"
                android:background="@drawable/corners_14_color_white_stroke_1_color_80000000"
                android:gravity="center"
                android:paddingStart="@dimen/dp_10"
                android:paddingEnd="@dimen/dp_10"
                android:text="@string/cancel_en"
                android:textColor="@color/color_80000000"
                android:textSize="@dimen/sp_16" />

            <TextView
                android:id="@+id/tev_confirm"
                android:layout_width="@dimen/dp_80"
                android:layout_height="@dimen/dp_40"
                android:layout_gravity="end"
                android:background="@drawable/corners_14_color_white_stroke_1_color_blue"
                android:gravity="center"
                android:paddingStart="@dimen/dp_10"
                android:paddingEnd="@dimen/dp_10"
                android:text="@string/confirm_en"
                android:textColor="@color/blue"
                android:textSize="@dimen/sp_16" />

        </FrameLayout>
    </LinearLayout>

</LinearLayout>

4、在res文件夹的drawable文件夹新建几个xml文件,并把一下的xml代码复制进去。

corners_14_color_white的drawable文件

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
 
    <corners android:radius="@dimen/dp_14" />
    <solid android:color="@color/white" />
</shape>


 corners_14_color_white_stroke_1_color_80000000的drawable文件

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
 
    <corners android:radius="@dimen/dp_14" />
    <solid android:color="@color/white" />
    <stroke
        android:width="@dimen/dp_1"
        android:color="@color/color_80000000" />
</shape>

corners_14_color_white_stroke_1_color_blue的drawable文件

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
 
    <corners android:radius="@dimen/dp_14" />
    <solid android:color="@color/white" />
    <stroke
        android:width="@dimen/dp_1"
        android:color="@color/blue" />
</shape>

4、在res文件夹的values文件夹的values.xml文件下加入dialog style。

<style name="dialog_decimal_style" parent="Theme.AppCompat.Dialog">
        <!-- dialog 背景颜色,默认是白色-->
        <item name="android:colorBackground">@android:color/transparent</item>
    </style>

如对此有疑问,请联系qq1164688204。

推荐Android开源项目

项目功能介绍:RxJava2和Retrofit2项目,添加自动管理token功能,添加RxJava2生命周期管理,使用App架构设计是MVP模式和MVVM模式,同时使用组件化,部分代码使用Kotlin,此项目持续维护中。

项目地址:https://gitee.com/urasaki/RxJava2AndRetrofit2

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值