Android自定义键盘

作者: 南歌ccc | 来源:发表于2018-11-17 16:46 被阅读31次

    最近项目有个新需求,需要自定义键盘。在强大的Android面前,这点问题当然是可以满足的,话不多说,开始撸起来。

    我们要实现如下图的效果:

    效果图

    首先是自定义键盘的xml文件:customer_key_board.xml


    customer_key_board
    <?xml version="1.0" encoding="UTF-8"?>
    <Keyboard android:keyWidth="10%p" android:keyHeight="8%p"
        android:horizontalGap="0.0px" android:verticalGap="0.0px"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <Row android:verticalGap="1%p">
            <Key android:codes="49" android:keyLabel="1"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"
                android:keyEdgeFlags="left"  />
            <Key android:codes="50" android:keyLabel="2"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="51" android:keyLabel="3"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="52" android:keyLabel="4"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="53" android:keyLabel="5"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="54" android:keyLabel="6"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="55" android:keyLabel="7"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="56" android:keyLabel="8"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="57" android:keyLabel="9"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="48" android:keyLabel="0"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"
                android:keyEdgeFlags="right"/>
        </Row>
    
        <Row android:verticalGap="1%p">
            <Key android:codes="81" android:keyLabel="Q"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"
                android:keyEdgeFlags="left" />
            <Key android:codes="87" android:keyLabel="W"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="69" android:keyLabel="E"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="82" android:keyLabel="R"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="84" android:keyLabel="T"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="89" android:keyLabel="Y"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="85" android:keyLabel="U"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="73" android:keyLabel="I"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="79" android:keyLabel="O"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="80" android:keyLabel="P"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"
                android:keyEdgeFlags="right" />
        </Row>
    
        <Row android:verticalGap="1%p">
            <Key android:codes="65" android:keyLabel="A"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"
                android:keyEdgeFlags="left" />
            <Key android:codes="83" android:keyLabel="S"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="68" android:keyLabel="D"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="70"  android:keyLabel="F"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="71" android:keyLabel="G"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="72"  android:keyLabel="H"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="74" android:keyLabel="J"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="75" android:keyLabel="K"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="76"  android:keyLabel="L"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"
                android:keyEdgeFlags="right" />
            <Key  android:codes="-5" android:keyEdgeFlags="right"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"
                android:isRepeatable="true" />
            <!--android:keyIcon="@drawable/keyboard_delete_bg"-->
        </Row>
    
        <Row >
            <Key android:codes="90" android:keyLabel="Z"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"
                android:keyEdgeFlags="left" />
            <Key android:codes="88" android:keyLabel="X"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="67" android:keyLabel="C"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="86" android:keyLabel="V"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="66" android:keyLabel="B"
                android:horizontalGap="1%p" android:keyWidth="8.9%p" />
            <Key android:codes="78" android:keyLabel="N"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"/>
            <Key android:codes="77" android:keyLabel="M"
                android:horizontalGap="1%p" android:keyWidth="8.9%p"/>
            <Key  android:codes="-4"
                android:keyEdgeFlags="right"
                android:horizontalGap="1%p" android:keyWidth="28.9%p"
                android:keyLabel="确定" android:isRepeatable="true" />
            <!--android:keyIcon="@drawable/keyboard_confirm_bg"-->
        </Row>
    
    </Keyboard>
    

    KeyBoard标签下的keyWidth="10%p"表示下面的每个键宽度占parent宽度的10%(Key标签下的keyWidth属性会覆盖parent中赋的值),horizontalGap是键与键之间的水平间隔,verticalGap是垂直间隔。
    Row标签代表行,Key标签代表键。

    拿第一行为例:Row标签里有10个Key标签,表示123...90 总共10个键,Key标签里的horizontalGap属性是键与键之间的水平间隔,keyWidth属性是键的宽度大小,在这里有一个计算关系,总共的键间隔宽度+总共的键宽度=你设置的键盘宽度,我这个键盘是全屏的,因此10个键宽度=10 * 8.9%p=89%屏幕宽度,有11个水平间隔宽度,每个水平间隔宽度1%,总水平间隔宽度=11 * 1%=11%,总宽度=89%+11%=100% 刚好一个屏幕宽度。具体的设计则灵活应变键的宽度和间隔宽度。

    最左边的键加入属性android:keyEdgeFlags="left",最右边的键加入属性 android:keyEdgeFlags="right"。
    codes属性一般是该Key对应的ASCII码,当然也可以自定义,只需要监听事件中返回给你这个codes值即可。keyLabel属性就是该Key显示在键盘上的string,还有个keyIcon属性是该Key显示在键盘上的drawable。
    Key标签下还有一个属性isRepeatable表示是长按时是否重复输入。

    接下来就是自定义键盘的代码了:

    /**
     * Created by hao on 2018/9/6.
     * 车牌号专用键盘
     */
    public class CarKeyboardView extends KeyboardView {
    
        public CarKeyboardView(Context context, AttributeSet attrs) {
            super(context, attrs, 0);
        }
    
        public CarKeyboardView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Keyboard keyboard = getKeyboard();
            if (keyboard == null) return;
            List<Keyboard.Key> keys = keyboard.getKeys();
            if (keys != null && keys.size() > 0) {
                @SuppressLint("DrawAllocation")
                Paint paint = new Paint();
                paint.setTextAlign(Paint.Align.CENTER);
                Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
                paint.setTypeface(font);
                paint.setAntiAlias(true);
                for (Keyboard.Key key : keys) {
                    if (key.codes[0] == -4) {
                        Drawable dr = getContext().getResources().getDrawable(R.drawable.keyboard_confirm_bg);
                        dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
                        dr.draw(canvas);
                        if (key.label != null) {
                            paint.setTextSize(ScreenUtils.sp2px(getContext(),18));
                            //设置字体颜色
                            paint.setColor(getContext().getResources().getColor(R.color.color_white));
                           // 注意: 这个方法不支持硬件加速,所以我们要测试时必须先关闭硬件加速。加上这一句
    //                        setLayerType(LAYER_TYPE_SOFTWARE, null);
    //                        paint.setShadowLayer(0.1f, 0, 0, getContext().getResources().getColor(R.color.color_white));
                            @SuppressLint("DrawAllocation")
                            Rect rect = new Rect(key.x, key.y, key.x + key.width, key.y + key.height);
                            Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
                            int baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;
                            // 下面这行是实现水平居中,drawText对应改为传入targetRect.centerX()
                            paint.setTextAlign(Paint.Align.CENTER);
                            canvas.drawText(key.label.toString(), rect.centerX(), baseline, paint);
    //                        paint.setShadowLayer(0, 0, 0, 0);
                        }
                    } else if (key.codes[0] == -5) {
                        Drawable dr = getContext().getResources().getDrawable(R.drawable.keyboard_delete_bg);
                        dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
                        dr.draw(canvas);
                    } else if (key.codes[0] == 73||key.codes[0] == 79) {  // notice 字母 I 和 O 设置特殊背景
                        Drawable dr = getContext().getResources().getDrawable(R.drawable.shape_keyboard_gray_color_r5);
                        dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
                        dr.draw(canvas);
                        if (key.label != null) {
                            paint.setTextSize(ScreenUtils.sp2px(getContext(),18));
                            paint.setColor(getContext().getResources().getColor(R.color.color_white_999999));
                            // 注意: 这个方法不支持硬件加速,所以我们要测试时必须先关闭硬件加速。加上这一句
    //                        setLayerType(LAYER_TYPE_SOFTWARE, null);
    //                        paint.setShadowLayer(0.1f, 0, 0, getContext().getResources().getColor(R.color.color_white_999999));
                            @SuppressLint("DrawAllocation")
                            Rect rect = new Rect(key.x, key.y, key.x + key.width, key.y + key.height);
                            Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
                            int baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;
                            paint.setTextAlign(Paint.Align.CENTER);
                            canvas.drawText(key.label.toString(), rect.centerX(), baseline, paint);
    //                        paint.setShadowLayer(0, 0, 0, 0);
                        }
                    }
                }
            }
        }
    }
    

    主要是继承KeyboardView ,重写onDraw方法,在onDraw方法里,根据不同的key.codes,设置不同的字体、字体颜色、按键背景等属性,这里的代码只是实现了我需要的需求,I、O键背景置灰,删除、确定键使用自定义的图片,不同需求做相应处理即可。

    接下来我们在处理一下点击监听等事件:封装进CarKeyBoardUtil里

    /**
     * Created by hao on 2018/9/6.
     * 车牌号专用键盘
     */
    public class CarKeyBoardUtil {
    
        private View keyboardParentView;
        private KeyboardView keyboardView;
        private EditText editText;
        private Keyboard keyboard;// 键盘
    
        public CarKeyBoardUtil(View keyboardParentView, KeyboardView keyboardView, EditText editText) {
            this.keyboardParentView = keyboardParentView;
            this.keyboardView = keyboardView;
            this.editText = editText;
    
            this.keyboard = new Keyboard(editText.getContext(), R.xml.car_key_board);
            this.editText.setInputType(InputType.TYPE_NULL);
            this.keyboardView.setOnKeyboardActionListener(listener);
            this.keyboardView.setKeyboard(keyboard);
            this.keyboardView.setEnabled(true);
            this.keyboardView.setPreviewEnabled(false);
        }
    
        private KeyboardView.OnKeyboardActionListener listener = new KeyboardView.OnKeyboardActionListener() {
    
            @Override
            public void swipeUp() {
            }
    
            @Override
            public void swipeRight() {
    
            }
    
            @Override
            public void swipeLeft() {
            }
    
            @Override
            public void swipeDown() {
            }
    
            @Override
            public void onText(CharSequence text) {
            }
    
            @Override
            public void onRelease(int primaryCode) {
            }
    
            @Override
            public void onPress(int primaryCode) {
            }
    
            @Override
            public void onKey(int primaryCode, int[] keyCodes) {
                Editable editable = editText.getText();
                int start = editText.getSelectionStart();
                switch (primaryCode) {
                    case Keyboard.KEYCODE_DELETE:
                        if (editable != null && editable.length() > 0) {
                            if (start > 0) {
                                editable.delete(start - 1, start);
                            }
                        }
                        break;
                    case Keyboard.KEYCODE_DONE:
                        if (runnable != null) {
                            keyboardView.postDelayed(runnable, 200);
                        } else {
                            if (keyboardParentView != null) {
                                keyboardParentView.setVisibility(View.GONE);
                            } else {
                                keyboardView.setVisibility(View.GONE);
                            }
                        }
                        break;
                    case 73:
                    case 79:
                        break;
                    default:
                        editable.insert(start, Character.toString((char) primaryCode));
                        break;
                }
            }
        };
    
        private Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (keyboardParentView != null) {
                    if (keyboardParentView.getVisibility() == View.VISIBLE) {
                        keyboardParentView.setVisibility(View.GONE);
                    }
                } else {
                    if (keyboardView != null) {
                        if (keyboardView.getVisibility() == View.VISIBLE) {
                            keyboardView.setVisibility(View.GONE);
                        }
                    }
                }
            }
        };
    
        public void showKeyboard() {
            if (keyboardParentView != null) {
                int visibility = keyboardParentView.getVisibility();
                if (visibility == View.GONE || visibility == View.INVISIBLE) {
                    keyboardParentView.setVisibility(View.VISIBLE);
                }
            } else {
                if (keyboardView == null) {
                    return;
                }
                int visibility = keyboardView.getVisibility();
                if (visibility == View.GONE || visibility == View.INVISIBLE) {
                    keyboardView.setVisibility(View.VISIBLE);
                }
            }
        }
    
        public void hideKeyboard() {
            if (keyboardParentView != null) {
                int visibility = keyboardParentView.getVisibility();
                if (visibility == View.VISIBLE) {
                    keyboardParentView.setVisibility(View.GONE);
                }
            } else {
                if (keyboardView == null) {
                    return;
                }
                int visibility = keyboardView.getVisibility();
                if (visibility == View.VISIBLE) {
                    keyboardView.setVisibility(View.GONE);
                }
            }
        }
    
        public int getKeyboardVisibility() {
            int visibility = View.GONE;
            if (keyboardParentView != null) {
                visibility = keyboardParentView.getVisibility();
    
            } else {
                if (keyboardView != null) {
                    visibility = keyboardView.getVisibility();
                }
            }
            return visibility;
        }
    }
    

    因为我这个键盘是用来输入车牌号码的,因此需求是字母I和字母O不可点击。我们只需要在OnKeyboardActionListener的onKey方法里,拦截codes为73(I)和79(O),不去处理即可。

    最后是使用:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <EditText
            android:id="@+id/act_key_board_et"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:inputType="text"
            tools:ignore="Autofill,LabelFor" />
        
        <LinearLayout
            android:id="@+id/ky_keyboard_parent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="#d1d5dd"
            android:orientation="vertical"
            android:paddingBottom="15dp"
            android:paddingTop="10dp"
            tools:ignore="RtlHardcoded">
    
            <!--自定义,随便改-->
            <com.hccf.widget.keyboard.CarKeyboardView
                android:id="@+id/ky_keyboard"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#d1d5dd"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:keyBackground="@drawable/keyboard_click_bg"
                android:keyTextColor="@color/edt_text_color"
                android:keyTextSize="20sp"
                android:shadowColor="#d1d5dd"
                android:shadowRadius="0.1" />
    
        </LinearLayout>
    
    </RelativeLayout>
    
    public class KeyBoardActivity extends AppCompatActivity {
    
        private EditText act_key_board_et;
        private CarKeyboardView keyboardView;
        private View ky_keyboard_parent;
        private CarKeyBoardUtil carKeyBoardUtil;
    
        @SuppressLint("ClickableViewAccessibility")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_key_board);
    
            act_key_board_et = findViewById(R.id.act_key_board_et);
            keyboardView = findViewById(R.id.ky_keyboard);
            ky_keyboard_parent = findViewById(R.id.ky_keyboard_parent);
            carKeyBoardUtil = new CarKeyBoardUtil(ky_keyboard_parent,keyboardView,act_key_board_et);
            act_key_board_et.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (carKeyBoardUtil == null) {
                        carKeyBoardUtil = new CarKeyBoardUtil(ky_keyboard_parent,keyboardView,act_key_board_et);
                    }
                    carKeyBoardUtil.showKeyboard();
                    return false;
                }
            });
        }
    }
    

    最终效果图如下:


    效果图

    另外在补充一个,也是很常见的自定义数字键盘:


    数字键盘

    具体实现就不在赘述,原理都差不多,代码直接贴上了。

    psd_key_board.xml

    <?xml version="1.0" encoding="utf-8"?>
    <Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
        android:horizontalGap="1dp"
        android:keyHeight="8%p"
        android:keyWidth="33.3333%p"
        android:verticalGap="1dp">
    
        <Row>
            <Key
                android:codes="49"
                android:keyLabel="1" />
            <Key
                android:codes="50"
                android:keyLabel="2" />
            <Key
                android:codes="51"
                android:keyLabel="3" />
        </Row>
    
        <Row>
            <Key
                android:codes="52"
                android:keyLabel="4" />
            <Key
                android:codes="53"
                android:keyLabel="5" />
            <Key
                android:codes="54"
                android:keyLabel="6" />
        </Row>
    
        <Row>
            <Key
                android:codes="55"
                android:keyLabel="7" />
            <Key
                android:codes="56"
                android:keyLabel="8" />
            <Key
                android:codes="57"
                android:keyLabel="9" />
        </Row>
    
        <Row>
            <Key
                android:codes="-10"
                android:keyLabel="" />
            <Key
                android:codes="48"
                android:keyLabel="0" />
            <Key
                android:codes="-5"
                android:keyLabel="" />
        </Row>
    </Keyboard>
    

    PwdKeyboardView.java

    /**
     * Created by jhn on 2018/9/20.
     * Description :
     */
    public class PwdKeyboardView extends KeyboardView implements KeyboardView.OnKeyboardActionListener {
        private static final String TAG = "PwdKeyboardView";
    
        private static final int KEY_EMPTY = -10;
    
        private int delKeyBackgroundColor = 0xffDADADA;
    
        private Rect keyIconRect;
    
        public PwdKeyboardView(Context context, AttributeSet attrs) {
            super(context, attrs);
            Log.d(TAG, "PwdKeyboardView: two params");
            init(context);
    
        }
    
        public PwdKeyboardView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            Log.d(TAG, "PwdKeyboardView: three params");
            init(context);
        }
    
        private void init(Context context) {
            Keyboard keyboard = new Keyboard(context, R.xml.psd_key_board);  // 初始化 keyboard
            setKeyboard(keyboard);
            setEnabled(true);
            setFocusable(true);
            setPreviewEnabled(false);  // 设置点击按键不显示预览气泡
            setOnKeyboardActionListener(this);
        }
    
        /**
         * 重新绘制删除按键和空白键
         */
        @Override
        public void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
            List<Keyboard.Key> keys = getKeyboard().getKeys();
            for (Keyboard.Key key : keys) {
                if (key.codes[0] == KEY_EMPTY) {
                    // 绘制空白键背景
                    drawKeyBackground(key, canvas, delKeyBackgroundColor);
                }
                if (key.codes[0] == Keyboard.KEYCODE_DELETE) {
                    // 删除删除按键背景
                    drawKeyBackground(key, canvas, delKeyBackgroundColor);
                    // 绘制删除按键图标
                    drawKeyIcon(key, canvas, getResources().getDrawable(R.drawable.icon_input_clear));
                }
            }
        }
    
        /**
         * 绘制按键的背景
         */
        private void drawKeyBackground(Keyboard.Key key, Canvas canvas, int color) {
            ColorDrawable drawable = new ColorDrawable(color);
            drawable.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
            drawable.draw(canvas);
        }
    
        /**
         * 绘制按键的 icon
         */
        private void drawKeyIcon(Keyboard.Key key, Canvas canvas, Drawable iconDrawable) {
            if (iconDrawable == null) {
                return;
            }
            // 计算按键icon 的rect 范围
            if (keyIconRect == null || keyIconRect.isEmpty()) {
                // 得到 keyicon 的显示大小,因为图片放在不同的drawable-dpi目录下,显示大小也不一样
                int intrinsicWidth = iconDrawable.getIntrinsicWidth();
                int intrinsicHeight = iconDrawable.getIntrinsicHeight();
                int drawWidth = intrinsicWidth;
                int drawHeight = intrinsicHeight;
                // 限制图片的大小,防止图片按键范围
                if (drawWidth > key.width) {
                    drawWidth = key.width;
                    // 此时高就按照比例缩放
                    drawHeight = (int) (drawWidth * 1.0f / intrinsicWidth * intrinsicHeight);
                } else if (drawHeight > key.height) {
                    drawHeight = key.height;
                    drawWidth = (int) (drawHeight * 1.0f / intrinsicHeight * intrinsicWidth);
                }
                // 获取图片的 x,y 坐标,图片在按键的正中间
                int left = key.x + key.width / 2 - drawWidth / 2;
                int top = key.y + key.height / 2 - drawHeight / 2;
                keyIconRect = new Rect(left, top, left + drawWidth, top + drawHeight);
            }
    
            if (keyIconRect != null && !keyIconRect.isEmpty()) {
                iconDrawable.setBounds(keyIconRect);
                iconDrawable.draw(canvas);
            }
        }
    
        @Override
        public void onPress(int primaryCode) {
    
        }
    
        @Override
        public void onRelease(int primaryCode) {
    
        }
    
        /**
         * 处理按键的点击事件
         */
        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            Log.d(TAG, "onKey: primaryCode = " + primaryCode + ", keyCodes = " + Arrays.toString(keyCodes));
            if (primaryCode == KEY_EMPTY) {
                return;
            }
            if (listener != null) {
                if (primaryCode == Keyboard.KEYCODE_DELETE) {
                    listener.onDelete();
                } else {
                    listener.onInput(String.valueOf((char) primaryCode));
                }
            }
        }
    
        @Override
        public void onText(CharSequence charSequence) {
    
        }
    
        @Override
        public void swipeLeft() {
    
        }
    
        @Override
        public void swipeRight() {
    
        }
    
        @Override
        public void swipeDown() {
    
        }
    
        @Override
        public void swipeUp() {
    
        }
    
        public interface OnKeyListener {
            // 输入回调
            void onInput(String text);
    
            // 删除回调
            void onDelete();
        }
    
        private OnKeyListener listener;
    
        public void setOnKeyListener(OnKeyListener listener) {
            this.listener = listener;
        }
    }
    

    attr.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="PwdEditText">
            <attr name="style" format="enum">
                <enum name="rectangle" value="0" />
                <enum name="roundRectangle" value="1" />
            </attr>
            <attr name="pwdCount" format="integer" />
            <attr name="strokeRadius" format="dimension" />
            <attr name="strokeWidth" format="dimension" />
            <attr name="strokeColor" format="color" />
            <attr name="dotColor" format="color" />
            <attr name="dotRadius" format="dimension" />
        </declare-styleable>
    
    </resources>
    

    自定义的输入框 PwdEditText.java

    /**
     * Created by jhn on 2018/9/20.
     * Description :
     */
    public class PwdEditText extends android.support.v7.widget.AppCompatEditText {
    
        private final int STYLE_RECTANGLE = 0;
        private final int STYLE_ROUND_RECTANGLE = 1;
        private final int DEFAULT_STYLE = STYLE_RECTANGLE;
        private final int DEFAULT_PWD_COUNT = 6;
        private final float DEFAULT_STROKE_RADIUS = dp2Px(6);
        private final float DEFAULT_STROKE_WIDTH = dp2Px(1);
        private final int DEFAULT_STROKE_COLOR = Color.parseColor("#CCCCCC");
        private final int DEFAULT_DOT_COLOR = Color.BLACK;
        private final float DEFAULT_DOT_RADIUS = dp2Px(4);
    
        private int style;   // 控件的样式,矩形或圆角矩形
        private float strokeRadius;  // 边框圆角的半径
        private float strokeWidth;   // 边框宽度
        private int strokeColor;  // 边框颜色
        private int pwdDotColor;  // 密码圆点颜色
        private float pwdDotRadius;  // 密码圆点半径
        private int mWidth;  // 控件宽度
        private int mHeight;  // 控件高度
        private Paint strokePaint;    // 绘制边框paint
        private Paint pwdDotPaint;    // 绘制密码圆点paint
        private int mCount;   // 密码框个数
        private float cellWidth;   // 每个密码框的宽度
        private float paddingWidth;
        private float halfStrokeWidth;
        private int mCurInputCount;  // 当前输入字符个数
    
        public PwdEditText(Context context) {
            this(context, null);
        }
    
        /**
         * 无论xml布局文件中有没有写自定义属性,都调用两个参数的构造函数
         */
        public PwdEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            initAttrs(context, attrs);
            init();
        }
    
        /**
         * 当有自定义的样式时,调用三个参数的构造函数
         */
        public PwdEditText(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        /**
         * 初始化自定义属性
         */
        private void initAttrs(Context context, AttributeSet attrs) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PwdEditText);
            style = typedArray.getInt(R.styleable.PwdEditText_style, DEFAULT_STYLE);
            mCount = typedArray.getInt(R.styleable.PwdEditText_pwdCount, DEFAULT_PWD_COUNT);
            strokeColor = typedArray.getColor(R.styleable.PwdEditText_strokeColor, DEFAULT_STROKE_COLOR);
            strokeWidth = typedArray.getDimension(R.styleable.PwdEditText_strokeWidth, DEFAULT_STROKE_WIDTH);
            strokeRadius = typedArray.getDimension(R.styleable.PwdEditText_strokeRadius, DEFAULT_STROKE_RADIUS);
            pwdDotColor = typedArray.getColor(R.styleable.PwdEditText_dotColor, DEFAULT_DOT_COLOR);
            pwdDotRadius = typedArray.getDimension(R.styleable.PwdEditText_dotRadius, DEFAULT_DOT_RADIUS);
            typedArray.recycle();
        }
    
        /**
         * 初始化操作
         */
        private void init() {
            // 初始化边框画笔
            strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            strokePaint.setColor(strokeColor);
            strokePaint.setStrokeWidth(strokeWidth);
            strokePaint.setStyle(Paint.Style.STROKE);
    
            // 初始化圆点画笔
            pwdDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            pwdDotPaint.setStyle(Paint.Style.FILL);
            pwdDotPaint.setColor(pwdDotColor);
    
            halfStrokeWidth = strokeWidth / 2;
    
            // 设置光标不可见
            setCursorVisible(false);
            // 设置限定最大长度
            setFilters(new InputFilter[]{new InputFilter.LengthFilter(mCount)});
            // 设置无背景
    //        setBackgroundColor(getResources().getColor(android.R.color.transparent));
            setBackgroundColor(Color.WHITE);
            setMaxLines(1);
            setFocusable(false);
    
            this.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    if (onTextChangedListener != null) {
                        onTextChangedListener.beforeTextChanged(s, start, count, after);
                    }
                }
    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (onTextChangedListener != null) {
                        onTextChangedListener.onTextChanged(s, start, before, count);
                    }
                    mCurInputCount = s.toString().length();
    
                    // 输入完成的回调
                    if (mCurInputCount == mCount) {
                        if (onTextInputListener != null) {
                            onTextInputListener.onComplete(s.toString());
                        }
                    }
                }
    
                @Override
                public void afterTextChanged(Editable s) {
                    if (onTextChangedListener != null) {
                        onTextChangedListener.afterTextChanged(s);
                    }
                }
            });
        }
    
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            mWidth = w;
            mHeight = h;
    //        cellWidth = (mWidth - strokeWidth) / mCount;
            paddingWidth = ScreenUtils.dp2px(getContext(), 15);
            float allPaddingWidth = paddingWidth * (mCount - 1);
            cellWidth = (mWidth - strokeWidth * mCount - allPaddingWidth) / mCount;
    //        Log.d(AppConfig.TAG, "paddingWidth---------->" + paddingWidth);
    //        Log.d(AppConfig.TAG, "allPaddingWidth---------->" + allPaddingWidth);
    //        Log.d(AppConfig.TAG, "cellWidth---------->" + cellWidth);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
    //        super.onDraw(canvas);  
            drawRect(canvas);
    //        drawHorizontalStroke(canvas);
    //        drawVerticalDivider(canvas);
            drawPwdDot(canvas);
        }
    
        private void drawPwdDot(Canvas canvas) {
            for (int i = 1; i <= mCurInputCount; i++) {
                canvas.drawCircle(halfStrokeWidth + cellWidth / 2 + (cellWidth + paddingWidth + strokeWidth) * (i - 1), (mHeight) / 2,
                        pwdDotRadius, pwdDotPaint);
    //            canvas.drawCircle(halfStrokeWidth + cellWidth / 2 + (cellWidth + paddingWidth) * (i - 1), (mHeight) / 2,
    //                    pwdDotRadius, pwdDotPaint);
            }
        }
    
        // 绘制矩形方块
        private void drawRect(Canvas canvas) {
            if (mCount == 1) {
                RectF rectF = new RectF(halfStrokeWidth, halfStrokeWidth, mWidth - halfStrokeWidth,
                        mHeight - halfStrokeWidth);
                canvas.drawRoundRect(rectF, strokeRadius, strokeRadius, strokePaint);
            } else {
                for (int i = 0; i < mCount; i++) {
                    // 画框框 左上,右下
                    float left;
                    if (i == 0) {
                        left = halfStrokeWidth;
                    } else {
                        left = halfStrokeWidth * (2 * i) + cellWidth * i + paddingWidth * i;
                    }
                    float top = strokeWidth / 2; // 就是halfStrokeWidth,语法不允许int x=0;y=x;
                    float right = halfStrokeWidth * (2 * i + 1) + cellWidth * (i + 1) + paddingWidth * i;
                    float bottom = mHeight - halfStrokeWidth;
                    RectF rectF = new RectF(
                            left,
                            top,
                            right,
                            bottom);
                    Log.d(getClass().getSimpleName(), "i------->" + i + "-----left------>" + left + "-----right----->" + right);
                    canvas.drawRoundRect(rectF, strokeRadius, strokeRadius, strokePaint);
                }
            }
        }
    
        // 绘制竖直方向分割线
        private void drawVerticalDivider(Canvas canvas) {
            if (mCount == 1) {
                return;
            }
            for (int i = 1; i < mCount; i++) {
                canvas.drawLine(halfStrokeWidth + cellWidth * i, halfStrokeWidth, halfStrokeWidth + cellWidth * i,
                        mHeight - halfStrokeWidth, strokePaint);
    
    //            // 第一條 line+cell*+padding*(i-1)
    //            canvas.drawLine(halfStrokeWidth + cellWidth * i + paddingWidth * (i - 1),
    //                    halfStrokeWidth,
    //                    halfStrokeWidth + cellWidth * i + paddingWidth * (i - 1),
    //                    mHeight - halfStrokeWidth,
    //                    strokePaint);
    //
    //            // 第二條 line+cell*+line*i+padding*i
    //            canvas.drawLine(halfStrokeWidth + cellWidth * i + paddingWidth * i,
    //                    halfStrokeWidth,
    //                    halfStrokeWidth + cellWidth * i + paddingWidth * i,
    //                    mHeight - halfStrokeWidth,
    //                    strokePaint);
            }
        }
    
        // 绘制水平方向分割线
        private void drawHorizontalStroke(Canvas canvas) {
    
            if (style == STYLE_RECTANGLE) {
                canvas.drawRect(halfStrokeWidth, halfStrokeWidth, mWidth - halfStrokeWidth,
                        mHeight - halfStrokeWidth, strokePaint);
            } else {
                RectF rectF = new RectF(halfStrokeWidth, halfStrokeWidth, mWidth - halfStrokeWidth,
                        mHeight - halfStrokeWidth);
                canvas.drawRoundRect(rectF, strokeRadius, strokeRadius, strokePaint);
            }
        }
    
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                return false;
            }
            return super.onKeyDown(keyCode, event);
        }
    
        private float dp2Px(int dpValue) {
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getResources().getDisplayMetrics());
        }
    
        public interface OnTextChangedListener {
            void beforeTextChanged(CharSequence s, int start, int count, int after);
    
            void onTextChanged(CharSequence s, int start, int before, int count);
    
            void afterTextChanged(Editable s);
        }
    
        public interface OnTextInputListener {
            void onComplete(String result);
    
        }
    
        private OnTextInputListener onTextInputListener;
    
        public void setOnTextInputListener(OnTextInputListener onTextInputListener) {
            this.onTextInputListener = onTextInputListener;
        }
    
        private OnTextChangedListener onTextChangedListener;
    
        public void addTextChangedListener(OnTextChangedListener listener) {
            this.onTextChangedListener = listener;
        }
    }
    

    fragment 弹出动画dialog_enter.xml

    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate
            android:duration="@android:integer/config_shortAnimTime"
            android:fromYDelta="100%p"
            android:toYDelta="0%p" />
    </set>
    

    fragment收回动画dialog_exit.xml

    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate
            android:duration="@android:integer/config_mediumAnimTime"
            android:fromYDelta="0%p"
            android:toYDelta="100%p" />
    </set>
    

    fragment布局文件 fgm_dialog_pay_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:orientation="vertical">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:orientation="horizontal"
            tools:ignore="UseCompoundDrawables">
    
            <ImageView
                android:id="@+id/iv_exit"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_margin="1dp"
                android:contentDescription="@string/app_name"
                android:padding="5dp"
                android:src="@drawable/icon_app_bar_close"
                tools:ignore="RtlHardcoded" />
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginEnd="52dp"
                android:gravity="center"
                android:text="输入交易密码"
                android:textColor="#494949"
                android:textSize="18sp" />
    
        </LinearLayout>
    
        <View
            android:layout_width="match_parent"
            android:layout_height="0.3dp"
            android:background="#EBEBEB" />
    
        <TextView
            android:id="@+id/tv_amount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:textColor="#807877"
            android:textSize="15sp"
            tools:text="提现金额9.00元" />
    
        <com.hao.pwdkeyboard.PwdEditText
            android:id="@+id/et_input"
            android:layout_width="match_parent"
            android:layout_height="55dp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="20dp"
            android:layout_marginRight="20dp"
            app:pwdCount="6"
            app:style="roundRectangle" />
    
        <View
            android:layout_width="match_parent"
            android:layout_height="0.3dp"
            android:layout_marginTop="35dp"
            android:background="#CCCCCC" />
    
        <com.hao.pwdkeyboard.PwdKeyboardView
            android:id="@+id/key_board"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#CCCCCC"
            android:keepScreenOn="true"
            android:keyBackground="@drawable/selector_key_board"
            android:keyTextColor="#494949"
            android:keyTextSize="26sp"
            android:shadowRadius="0" />
    
    </LinearLayout>
    

    最后就是PayDialogFragment.java

    /**
     * Created by jhn on 2018/9/20.
     * Description :
     */
    public class PayDialogFragment extends DialogFragment implements PwdEditText.OnTextInputListener {
    
        private static final String TAG = "PayDialogFragment";
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
        }
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container,
                                 @Nullable Bundle savedInstanceState) {
            Log.d(TAG, "onCreateView: ");
            //去掉dialog的标题,需要在setContentView()之前
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
            getDialog().setCanceledOnTouchOutside(false);
            View view = inflater.inflate(R.layout.fgm_dialog_pay_layout, null);
            ImageView exitImgView = view.findViewById(R.id.iv_exit);
            exitImgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PayDialogFragment.this.dismiss();
                }
            });
            final PwdEditText editText = view.findViewById(R.id.et_input);
            editText.setOnTextInputListener(this);
            PwdKeyboardView keyboardView = view.findViewById(R.id.key_board);
            keyboardView.setOnKeyListener(new PwdKeyboardView.OnKeyListener() {
                @Override
                public void onInput(String text) {
                    Log.d(TAG, "onInput: text = " + text);
                    editText.append(text);
                    String content = editText.getText().toString();
                    Log.d(TAG, "onInput: content = " + content);
                }
    
                @Override
                public void onDelete() {
                    Log.d(TAG, "onDelete: ");
                    String content = editText.getText().toString();
                    if (content.length() > 0) {
                        editText.setText(content.substring(0, content.length() - 1));
                    }
                }
            });
            return view;
        }
    
        @Override
        public void onStart() {
            super.onStart();
            Log.d(TAG, "onStart: ");
            Window window = getDialog().getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.windowAnimations = R.style.DialogFragmentAnimation;
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            //设置dialog的位置在底部
            lp.gravity = Gravity.BOTTOM;
            window.setAttributes(lp);
            //去掉dialog默认的padding
    //        window.getDecorView().setPadding(0, 0, 0, 0);
    
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
    
        @Override
        public void onComplete(String result) {
            Log.d(TAG, "onComplete: result = " + result);
            Toast.makeText(getContext(), "input complete : " + result, Toast.LENGTH_SHORT).show();
        }
    }
    

    使用的时候去操控这个PayDialogFragment就可以了。
    例如:

     PayDialogFragment payDialogFragment = new PayDialogFragment();
     payDialogFragment.show(getSupportFragmentManager(), "payFragment");
    

    讲述了2种自定义键盘,如果改动不是很大,可以直接使用系统提供的KeyboardView,支持一部分属性更改,但是如果改动较大则需要自己去重写一个继承自KeyboardView的CustomerKeyboardView,具体实现根据不同的需求来做调整,这方面Android提供了足够的开放。

    相关文章

      网友评论

        本文标题:Android自定义键盘

        本文链接:https://www.haomeiwen.com/subject/qhimfqtx.html