虽然android有许许多多的控件满足大多数需求,但是总会有一些情况下需要我们编写自定义控件满足自己的需求,而这边文章就是讲述学习自定义控件中复合控件的编写的心得。
编写复合控件首先需要在res/values 文件夹中创建attrs.xml文件,一个简单的例子如下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TopBar">
<attr name="titleText" format="string"/>
<attr name="titleTextSize" format="dimension"/>
<attr name="titleTextColor" format="color"/>
<attr name="leftTextColor" format="color"/>
<attr name="leftBackground" format="reference|color"/>
<attr name="leftText" format="string"/>
<attr name="rightTextColor" format="color"/>
<attr name="rightBackground" format="reference|color"/>
<attr name="rightText" format="string"/>
</declare-styleable>
</resources>
这里的
<declare-styleable name="TopBar">声明了一个名字叫TopBar的复合控件
下列的
<attr name="titleTextSize" format="dimension"/>
则是声明一个名字叫titleTextSize的属性,类型是demension
之后我们可以在res/layout文件夹创建这个控件的布局
<com.example.lalala.choosepictest.TopBar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom = "http://schemas.android.com/apk/res-auto"
android:id="@+id/topBar"
android:layout_width="match_parent"
android:layout_height="40dp"
custom:leftBackground="@drawable/ic_reply_black_48dp"
custom:leftText="返回"
custom:leftTextColor="#FFFFFF"
custom:rightBackground="@drawable/ic_apps_black_48dp"
custom:rightText="啦"
custom:rightTextColor="#FFFFFF"
custom:title="标题"
custom:titleTextColor="#112345"
custom:titleTextSize="15sp"
>
</com.example.lalala.choosepictest.TopBar>
将自己声明的属性按照安卓原生控件的方法赋值,需要注意添加
xmlns:custom = "http://schemas.android.com/apk/res-auto"表明需要使用自定义属性