自定义View(二)之自定义属性

昨天分享了简单的自定义View里面有用到自定义属性,所以在这里我对自定义属性作出总结。
自定义属性地第一步在Values文件夹下创建一个XML这里XML的名字可以随便起但是一般都是以attrs开头如attrs_circle.xml
先上布局代码然后在对代码中的内容作出总结

文件路径res/values/attrs_circle.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCircleView">
    <attr name="color" format="color"/>
</declare-styleable>
</resources>

declare-styleable自定义属性
attr中的format中的Color指的是格式 我这里的代码代表颜色除了color之外还有reference代表的是资源id,dimension代表尺寸,当然这里还有一些基本的数据类型这里我就不做过多的解释

自定义属性说完之后那么现在就来说说怎么使用在我们自定义View中这里我只贴出自定义属性这块代码,其他代码请在自定义VIew成长子路(一)中查看

 public MyCircleView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        //解析自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCircleView);
        mColor =typedArray.getColor(R.styleable.MyCircleView_color,Color.RED);
    }

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCircleView);

attrs参数为自定义VIew中构造中 R.styleable.MyCircleView为 declare-styleable后面的name

typedArray.getColor(R.styleable.MyCircleView_color,Color.RED);
R.styleable.MyCircleView_color 为attr中的name Color.RED为当我们没有设置时默认的颜色

布局文件中使用

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:circle="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    tools:context="com.example.as.myapplication.Main2Activity">

    <com.example.as.myapplication.MyCircleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        circle:color="#ffff"/>

</RelativeLayout>

xmlns:circle=”http://schemas.android.com/apk/res-auto”这句代码是对我们自定义属性的声明

circle:color=”#ffff”这句代码是对自定义属性声明后进行使用
好了自定义属性就在这了欢迎补充

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值