android复合控件的学习

虽然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"
表明需要使用自定义属性




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值