Android 自定义View一(自定义属性)

这里重温一下自定义View的开发流程,以下将完整的流程走一遍包括自定义属性、onDraw()、等。

继承View类


创建一个类并继承View类,当然如果需求不是很特别的话可以直接继承Android现有的控件拓展开发比如Button等,这些现有的控件类也是继承与View类

继承View类后创建至少一个的构造函数并执行super(context, attrs);

    /**
     * 有多个构造函数默认需要实现有两个构造参数的构造函数
     * @param context 上下文
     * @param attrs Xml自定义属性通过这个类传递进来
     */
    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

自定义属性


在XML布局中可以使用我们自定义的属性,并通过构造函数传递到类的实体中:

  1. 在res/values/attrs.xml声明自定义属性
  2. 在使用到自定义控件的layout中加入自身的命名空间
  3. 在自定义控件实体类的构造函数中获取属性值

声明自定义属性, name值一般为自定义控件的实体类名

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="CustomView">
        <attr name="isShow" format="boolean" />
        <attr name="align" format="enum">
            <enum name="left" value="1" />
            <enum name="right" value="2" />
        </attr>
    </declare-styleable>

</resources>

添加命名控件xmlns:app=”http://schemas.android.com/apk/res-auto”

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

    <com.example.xiaoxini2000.customview.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:isShow="true"
        app:align="left"
        />

</android.support.constraint.ConstraintLayout>

在实体构造函数中获取属性value 注意:这里TypedArray 因为是共享资源,所以结尾一定要释放

    /**
     * 有多个构造函数默认需要实现有两个构造参数的构造函数
     * @param context 上下文
     * @param attrs Xml自定义属性通过这个类传递进来
     */
    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = null;
        try {
            typedArray = context.getTheme().obtainStyledAttributes(attrs,R.styleable.CustomView,0,0);
            isShow = typedArray.getBoolean(R.styleable.CustomView_isShow,false);
            align = typedArray.getIndex(R.styleable.CustomView_align);
        }finally {
            typedArray.recycle();
        }

    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值