Android 自定义安全软键盘 SafeKeyboard 开发详细说明 2.0
源码地址:GitHub: https://github.com/SValence/SafeKeyboard
注意事项:SafeKeyboard 注意事项
一、Android 安全软键盘开发流程
1. 建立软键盘样式
-
即在项目
res 文件夹
下 新建xml 文件夹
, 并在该文件夹中创建所需要的各种软键盘的样式(比如说:字母、数字、符号 等) -
如下图所示:
2. 创建 layout
布局文件
- 在布局文件中给软键盘创建container,以便显示软键盘
3. 自定义 KeyboardView
- 自定义一个KeyboardView 并继承自KeyboardView,在自定义的KeyboardView中绘制特殊按键,包括按键的点击背景,图片,文字 等
4. 自定义一个普通 java
类,一般取名为 **Keyboard.java
-
把软键盘加载到container中,即在布局文件里预留的存放软键盘 的container
-
在类的内部实现软键盘的输入控制,键盘转换控制,软键盘的显示与隐藏控制 等
-
在需要用到软键盘的界面中实例化该
Keyboard
类,并传入必要的数据和信息
5. 效果图
- 如下图所示:
二、 Android
安全软键盘开发实例解析(仅作参考)
1. 创建项目后, 在 layout
布局文件中设计基本布局,参考如下
<!-- 详情请查看项目中 activity_main.xml 文件 -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/normalEditText"
android:layout_width="match_parent"
android:layout_height="50sp"
android:layout_marginStart="10sp"
android:layout_marginEnd="10sp"
android:hint="@string/keyboard_system"
android:inputType="text" />
<EditText
android:id="@+id/safeEditText"
android:layout_width="match_parent"
android:layout_height="50sp"
android:layout_marginStart="10sp"
android:layout_marginEnd="10sp"
android:hint="@string/keyboard_demo_new"
android:inputType="textVisiblePassword" />
<EditText
android:id="@+id/safeEditText2"
android:layout_width="match_parent"
android:layout_height="50sp"
android:layout_marginStart="10sp"
android:layout_marginEnd="10sp"
android:hint="@string/keyboard_demo_new2"
android:inputType="number" />
<EditText
android:id="@+id/safeEditText3"
android:layout_width="match_parent"
android:layout_height="50sp"
android:layout_marginStart="10sp"
android:layout_marginEnd="10sp"
android:hint="@string/keyboard_demo_new3" />
</LinearLayout>
<LinearLayout
android:id="@+id/keyboardViewPlace"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" />
</RelativeLayout>
-
这里使用一个线性布局作为存放自定义软键盘的容器,说明一下:
-
一般使用到自定义软键盘的页面的布局不会很复杂,无非就是想要在输入关键数据比如密码时才使用到软键盘,而软键盘一般都是在手机等移动设备屏幕的最下方显示,以方便输入,所以这里使用了
RelativeLayout
方便显示,当然也可以使用现在google
推行的ConstraintLayout
布局来做,这个根据个人喜好。 -
所以在原有的项目里加入一个存放软键盘的容器,也不会给原有的项目带来很大的麻烦或者影响,所以这种做法,我个人认为还是可取的.
2. 在项目 res
文件夹下创建 xml
文件夹,并创建出自己需要的软键盘布局,比如说:数字,字母,符号等
- 字母键盘布局示例:
<!-- 详情及其他键盘布局请查看项目中 /res/xml 文件夹 -->
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:horizontalGap="1%p"
android:keyHeight="@dimen/key_height"
android:keyWidth="10%p"