1.背景
最近在做把枪项目的过程中遇到这样一个需求,有一个客户在用把枪的过程中嫌把枪屏幕太小了,于是就用把枪连接pad使用,在pad上看商品的信息。这是就遇到一个问题,当把枪与pad连接上以后系统键盘无法弹出,试了一下别的第三方键盘也是无法弹出,于是只能用一个自定义View的方式去写一个简单的键盘(包括0~9,回车键和删除键)去解决这个问题。
2.实现分析
其实软键盘的功能不论在哪一个活动中,相同按钮所要实现的功能都是相同的。如果在每一个活动中的布局文件中都要重新添加按钮,无疑又是增加了很多重复的代码,这种情况下最好是使用自定义控件的方式来解决。
要通过自定义控件的方式去实现于上面效果图一样的控件效果我们需要将这些按钮进行一次封装,我们不可能在每个界面的布局文件中去一个个的添加按钮,其实上面的图片跟我们常用的布局LinearLayout或者RelativeLayout是一样的,不同的是在LinearLayout或者RelativeLayout的布局中需要加上0~9,回车键和删除键这几个按钮。首先我们先要在一个布局文件中去进行封装。
(1)我们需要在一个布局文件中按顺序添加按钮
(2)新建自定义控件KeyboardView继承自LinearLayout
(3)直接将自定义控件插入到需要软键盘的界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#b5b5b6"
android:orientation="horizontal" >
<Button
android:id="@+id/one"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"
android:background="@drawable/keyboard_selector_one"/>
<Button
android:id="@+id/two"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"
android:background="@drawable/keyboard_selector_two"/>
<Button
android:id="@+id/three"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"
android:background="@drawable/keyboard_selector_three"/>
<Button
android:id="@+id/four"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"
android:background="@drawable/keyboard_selector_four"/>
<Button
android:id="@+id/five"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"
android:background="@drawable/keyboard_selector_five"/>
<Button
android:id="@+id/six"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"
android:background="@drawable/keyboard_selector_six"/>
<Button
android:id="@+id/seven"
android:layout_height="wrap_content"
android:layout_weight="1"