android 自定义view(1)

第一步,在attrs中,新建该view在xml布局文件中所需要的自定义属性

values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <attr name="titleText" format="string" />
    <attr name="titleTextColor" format="color" />
    <attr name="titleTextSize" format="dimension" />

    <declare-styleable name="CustomTitleView">
        <attr name="titleText" />
        <attr name="titleTextColor" />
        <attr name="titleTextSize" />
    </declare-styleable>

</resources>

第二步,在该view的构造函数中,AttributeSet attrs参数可以获取到布局文件中应用到的所有的属性

public CustomTitleView(Context context, @Nullable AttributeSet attrs) {

    }

比如在如下布局中,AttributeSet attrs中包含了layout_width,layout_height,titleText,titleTextColor,titleTextSize等属性及其值。
需要特别注意到的有:
1. 自定义的属性与系统属性的前缀是不同的
2. 自定义的属性的前缀需要声明,如下所示 xmlns:custom=”http://schemas.android.com/apk/res-auto

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <self.com.customerview.CustomTitleView
        android:layout_width="200dp"
        android:layout_height="100dp"
        custom:titleText="3712"
        custom:titleTextColor="#ff0000"
        custom:titleTextSize="40sp" />

</RelativeLayout>

在View的构造函数中,获取到这些属性值,重写onDraw,onMeasure。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值