此文接着《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>