android 自定义系统键盘

1  在res下新建xml文件夹,有的话就略过,在xml新建类似keyboard.xml文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:horizontalGap="40px"
    android:keyHeight="16%p"
    android:keyWidth="16%p"
    android:verticalGap="40px">
    <Row>
        <Key
            android:codes="49"
            android:keyLabel="1" />
        <Key
            android:codes="50"
            android:keyLabel="2" />
        <Key
            android:codes="51"
            android:keyLabel="3" />
        <Key
            android:codes="-5"
            android:keyLabel="回删" />
    </Row>
    <Row>
        <Key
            android:codes="52"
            android:keyLabel="4" />
        <Key
            android:codes="53"
            android:keyLabel="5" />
        <Key
            android:codes="54"
            android:keyLabel="6" />
        <Key
            android:codes="@integer/keycode_empty_text"
            android:keyLabel="清除" />
    </Row>
    <Row>
        <Key
            android:codes="55"
            android:keyLabel="7" />
        <Key
            android:codes="56"
            android:keyLabel="8" />
        <Key
            android:codes="57"
            android:keyLabel="9" />
        <Key
            android:codes="@integer/keycode_confirm"
            android:keyEdgeFlags="right"
            android:keyHeight="36%p"
            android:keyLabel="确定" />
    </Row>
    <Row>
        <Key
            android:codes="46"
            android:keyLabel="."
            android:keyWidth="25%p"
            android:keyEdgeFlags="left"/>
        <Key
            android:codes="48"
            android:keyLabel="0"
            android:keyWidth="25%p" />
        <Key
            android:codes="@integer/keycode_00"
            android:keyLabel="00"
            android:keyWidth="25%p"
            android:horizontalGap="13%p"/>

    </Row>
</Keyboard>

 

2 在values文件夹下新建  custom_keyboard.xml  内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--基础键盘-->
    <integer name="keycode_empty_text">-10000</integer>
    <!--隐藏键盘-->
    <integer name="keycode_hide_keyboard">-10001</integer>

    <!--确定-->
    <integer name="keycode_confirm">-10002</integer>
    <!--00-->
    <integer name="keycode_00">-10003</integer>

</resources>

 

3 在activity布局文件中,添加如下代码     示例:

<?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="match_parent"
    android:layout_height="match_parent"
    tools:context="com.czb.utildemo.MainActivity"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:hint="请输入金额" />

    <android.inputmethodservice.KeyboardView
        android:id="@+id/main_keyview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="44px"
        android:layout_marginRight="44px"
        android:background="#ffffff"//键盘背景颜色
        android:duplicateParentState="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:keyBackground="@drawable/key_selector"//点击效果
        android:keyTextColor="#262626"//文字颜色
        android:keyTextSize="66px"//key文字大小
        android:labelTextSize="43px"//自定义文字大小
        android:shadowRadius="0" />
</LinearLayout>

4  添加工具类:

package com.czb.czbsumiost1.utils;

import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import com.czb.czbsumiost1.MyAppLication;
import com.czb.czbsumiost1.R;
import com.czb.czbsumiost1.utils.eventbus.Event;
import com.czb.czbsumiost1.utils.eventbus.EventBusUtil;

/**
 * Created by czb365 on 2017/11/16.
 */

public class KeyUtils {
    private Context mContext;
    private KeyboardView mKeyboardView;
    private Keyboard mKeyboard;
    private EditText etCurrent;

    public KeyUtils(Context context, KeyboardView keyboardView, EditText editText) {
        mContext = context;
        this.etCurrent = editText;
        //初始化键盘布局,下面在放进 KeyBoardView里面去。
        mKeyboard = new Keyboard(mContext, R.xml.keyboard);
        //配置keyBoardView
        try {
            mKeyboardView = keyboardView;
            mKeyboardView.setKeyboard(mKeyboard); 
            mKeyboardView.setPreviewEnabled(false); //按住键盘出来的预览图。
            mKeyboardView.setOnKeyboardActionListener(mListener);
        } catch (Exception e) {
            Log.e("sun", "keyview初始化失败" + e.getMessage());
        }
    }


    //监听
    private KeyboardView.OnKeyboardActionListener mListener = new KeyboardView.OnKeyboardActionListener() {

        @Override
        public void onPress(int primaryCode) {
//            Log.e("sun", "onPress=======:" + primaryCode);
        }

        @Override
        public void onRelease(int primaryCode) {
//            Log.e("sun", "onRelease====:" + primaryCode);
        }

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
//            Log.e("sun", "onkey=====primaryCode:" + primaryCode + "");

            if (null == etCurrent) return;
            if (!etCurrent.hasFocus()) {
                MyAppLication.requestFocus(etCurrent);
                EventBusUtil.sendEvent(new Event(C.EventCode.HIDE_KEYBOARD));
            }

            Editable editable = etCurrent.getText();
            int start = etCurrent.getSelectionStart();

            if (primaryCode == Keyboard.KEYCODE_DELETE) { //回退
                if (!TextUtils.isEmpty(editable)) {
                    if (start > 0) {
                        editable.delete(start - 1, start);
                    }
                }
            } else if (primaryCode == getKeyCode(R.integer.keycode_empty_text)) { //清空
                editable.clear();
            } else if (primaryCode == 46) { //小数点
//                    if (!editable.toString().contains(".")) {
//                        editable.insert(start, Character.toString((char) primaryCode));
//                    }
            } else if (primaryCode == getKeyCode(R.integer.keycode_00)) { //00
                editable.insert(start, "00");

            } else if (primaryCode == getKeyCode(R.integer.keycode_confirm)) { //确定
                EventBusUtil.sendEvent(new Event(C.EventCode.CONFIRM_SCAN_CODE, editable));
            } else { //其他默认
                editable.insert(start, Character.toString((char) primaryCode));
            }


        }

        @Override
        public void onText(CharSequence charSequence) {

        }

        @Override
        public void swipeLeft() {
//            Log.e("sun", "swipeLeft");
        }

        @Override
        public void swipeRight() {
//            Log.e("sun", "swipeRight");
        }

        @Override
        public void swipeDown() {
//            Log.e("sun", "swipeDown");
        }

        @Override
        public void swipeUp() {
//            Log.e("sun", "swipeUp");
        }

    };

    protected int getKeyCode(int resId) {
        if (null != etCurrent) {
            return etCurrent.getContext().getResources().getInteger(resId);
        } else {
            return Integer.MIN_VALUE;
        }
    }
}

5 在activity中使用

new KeyUtils(getActivity(), binding.mainKeyview, binding.codeInput);

 

 

6.改变某个按钮背景色或文字颜色:

 

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.Keyboard.Key;
import android.inputmethodservice.KeyboardView;
import android.util.AttributeSet;

import java.lang.reflect.Field;
import java.util.List;

public class MyKeyBoardView extends KeyboardView {
    private Context  mContext;
    private Keyboard mKeyBoard;

    public MyKeyBoardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

    public MyKeyBoardView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
    }

    /**
     * 重新画一些按键
     */
    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mKeyBoard = this.getKeyboard();
        List<Key> keys = null;
        if (mKeyBoard != null) {
            keys = mKeyBoard.getKeys();
        }

        if (keys != null) {
            for (Key key : keys) {
                // 数字键盘的处理
                if (key.codes[0] == -4) {
                    drawKeyBackground(R.drawable.bg_keyboardview_yes, canvas, key);
                    drawText(canvas, key);
                }
            }
        }
    }

    private void drawKeyBackground(int drawableId, Canvas canvas, Key key) {
        Drawable npd = mContext.getResources().getDrawable(
                drawableId);
        int[] drawableState = key.getCurrentDrawableState();
        if (key.codes[0] != 0) {
            npd.setState(drawableState);
        }
        npd.setBounds(key.x, key.y, key.x + key.width, key.y
                + key.height);
        npd.draw(canvas);
    }

    private void drawText(Canvas canvas, Key key) {
        Rect bounds = new Rect();
        Paint paint = new Paint();
        paint.setTextAlign(Paint.Align.CENTER);


        paint.setAntiAlias(true);

        paint.setColor(Color.WHITE);
        if (key.label != null) {
            String label = key.label.toString();

            Field field;

            if (label.length() > 1 && key.codes.length < 2) {
                int labelTextSize = 0;
                try {
                    field = KeyboardView.class.getDeclaredField("mLabelTextSize");
                    field.setAccessible(true);
                    labelTextSize = (int) field.get(this);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                paint.setTextSize(labelTextSize);
                paint.setTypeface(Typeface.DEFAULT_BOLD);
            } else {
                int keyTextSize = 0;
                try {
                    field = KeyboardView.class.getDeclaredField("mLabelTextSize");
                    field.setAccessible(true);
                    keyTextSize = (int) field.get(this);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                paint.setTextSize(keyTextSize);
                paint.setTypeface(Typeface.DEFAULT);
            }

            paint.getTextBounds(key.label.toString(), 0, key.label.toString()
                    .length(), bounds);
            canvas.drawText(key.label.toString(), key.x + (key.width / 2),
                    (key.y + key.height / 2) + bounds.height() / 2, paint);
        } else if (key.icon != null) {
            key.icon.setBounds(key.x + (key.width - key.icon.getIntrinsicWidth()) / 2, key.y + (key.height - key.icon.getIntrinsicHeight()) / 2,
                    key.x + (key.width - key.icon.getIntrinsicWidth()) / 2 + key.icon.getIntrinsicWidth(), key.y + (key.height - key.icon.getIntrinsicHeight()) / 2 + key.icon.getIntrinsicHeight());
            key.icon.draw(canvas);
        }

    }
}

 

 

转载于:https://my.oschina.net/u/1268043/blog/1607896

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值