Android快速自定义控件+实战演示(三)完整键盘和组合回调!

此文接着《Android快速自定义控件+实战演示(二)组合自定义view+回调》继续讲解。

这一节会提供的知识点:
1.如何把之前做好的单一控件组合成一个完整的键盘控件
2.如何在新的键盘控件里进行回调操作,使得能够选中点击某个数字/字母时,进行相关操作(比如打印出来)

回顾一下项目目标

我们要实现一种用在机顶盒端的自定义键盘,效果图如下
这里写图片描述

在上一节,我们已经实现了单个自定义按键的切换,现在就是通过布局,把它们排列成九宫格(如果包括最下面一行应该是十二宫格)就可以了。

自定义键盘

看了前两节教程,现在是不是觉得自定义控件超简单的。

自定义布局

首先取名custom_keyboard.xml,因为按键与按键之间有重叠的部分(所有按键都以圆盘形式展开的话,可发现有重叠),我用了RelativeLayout,所以自定义view的时候继承RelativeLayout。

自定义View类

新建一个类,名为CustomKeyboard.java继承RelativeLayout。
依旧在所有构造方法里加上我们的新方法load(),在load()方法里初始化布局(inflateLayout()),UI(initUI())和数据(initData())。
在布局里引入custom_keyboard.xml

    /**
     * @Description inflate the main layout
     */
    private void inflateLayout() {
        try {
            LayoutInflater.from(getContext()).inflate(R.layout.custom_keyboard, this, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

initUI()里将所有的按键获取到,包括清空和删除按钮。

    /**
     * @Description initialize the ui
     */
    private void initUI() {
        mItem1 = (CustomNumKeyboardItem) findViewById(R.id.item1); //数字1只用了数字按键,而不是组合按键,因为数字1下面没有字母,所以也不会出现圆盘按键
        mItem2 = (CustomKeyboardItem) findViewById(R.id.item2);
        mItem3 = (CustomKeyboardItem) findViewById(R.id.item3);
        mItem4 = (CustomKeyboardItem) findViewById(R.id.item4);
        mItem5 = (CustomKeyboardItem) findViewById(R.id.item5);
        mItem6 = (CustomKeyboardItem) findViewById(R.id.item6);
        mItem7 = (CustomKeyboardItem) findViewById(R.id.item7);
        mItem8 = (CustomKeyboardItem) findViewById(R.id.item8);
        mItem9 = (CustomKeyboardItem) findViewById(R.id.item9);
        //最后一行没有使用自定义view
        mItem0 = (Button) findViewById(R.id.item0);
        mItemClear = (ImageButton) findViewById(R.id.itemClear);
        mItemDelete = (ImageButton) findViewById(R.id.itemDelete);
    }

因为键盘的ABC…以及数字排列都是固定的,我们把数据以数组的格式存在custom_keyboard_arrays.xml里面

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="item1">
        <item>"1"</item>
    </string-array>
    <string-array name="item2">
        <item>"2"</item>
        <item>"A"</item>
        <item>"B"</item>
        <item>"C"</item>
    </string-array>
  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值