Android自定义View—KeyboardView

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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值