自定义键盘

UI布局

在xml包(如果没有,自己在res包下新建一个)中创建一个键盘布局num_keyboard_nine.xml

  • Keyboard基本需要设置每个按键的width和height,还有Gap
  • 设置Row,设计每一行的键盘
  • 设置codes,主要是键盘上的字符的ASCII码
  • 设置keyLabel,用于显示在键盘上
  • 设置keyIcon,用图标代替lable显示(不能跟keyLabel同时使用)
  • 设置isRepeatable,设置是否长按时,可以重复输入
  • 设置keyEdgeFlag,设置该键的边界
  • 问题1: keyLabel的字符个数若大于1,那么该按键的字体显示效果,将于默认的不同。字体会缩小,并且是加粗字体。
  • 解决: 以上的问题找了很多资料,后来发现在源码中有这么一段:

    1
    2
    3
    4
    5
    6
    7
    8
    // For characters, use large font. For labels like "Done", use small font.
    if (label.length() > 1 && key.codes.length < 2) {
    paint.setTextSize(mLabelTextSize);
    paint.setTypeface(Typeface.DEFAULT_BOLD);
    } else {
    paint.setTextSize(mKeyTextSize);
    paint.setTypeface(Typeface.DEFAULT);
    }

    从上面的源码可以看到,官方在这里做了一些处理。所以,咱们可以设置codes的个数大于两个从而绕过这一段代码。

    layout中使用View

    主要是用到keyboardView或者自定义一个view继承自keyboardView。下面用原生控件来举例。

  • 直接使用官方的keyboardView。注意使用标签来引用大概如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <android.inputmethodservice.KeyboardView
    android:id="@+id/keyboard_nine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/keyBoard"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:keyBackground="@drawable/keyback"
    android:keyTextColor="@color/keyColor"
    android:keyTextSize="@dimen/font_24"
    android:shadowRadius="0.0"
    android:visibility="gone">
    </android.inputmethodservice.KeyboardView>
  • keyBackground,设置按键的背景

  • 创建的时候需要在OnCreate中使用

    1. new一个键盘布局,并引用自己定义的键盘布局

      1
      Keyboard keyboard = new Keyboard(getContext(),R.xml.num_keyboard_nine);
    2. 将KeyboardView与布局绑定

      1
      2
      mKeyboardView = (KeyboardView)findViewById(R.id.keyboard_nine);
      mKeyboardView.setKeyboard(keyboard);
    3. 使用自定义的CustomKeyboard进行组装

      1
      customKeyboard = new CustomKeyboard(getActivity(), keyboard, mKeyboardView);

自定义类进行封装

使用自定义的组装类,可以大幅度实现案件功能上的自定义
CustomKeyboard.java