(总结)自定义属性

自定义View的自定义属性

 

 

1.在 values 文件中,新建attrs.xml 文件(如果原来没有), 内容大致是这样,

 

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

<resources>

     <!--自定义圆角imageview属性-->

    <declare-styleable name="RoundImageView">

        <attr name="xhradius" format="dimension"></attr>

        <attr name="xhtype">

            <enum name="fillet" value="0"></enum>

            <enum name="round" value="1"></enum>

        </attr>

    </declare-styleable>

</resources>

 

解读一下,<declare-styleable name="RoundImageView"> 申明一个控件

,其中 name="RoundImageView" 是定义这个控件的 那个java类的名称.

 

<attr name="xhradius" format="dimension"></attr> 就是自定义的一条属性,申明了属性的名称和属性的类型。

 

2.在 自定义Viewjava类中,使用几个构造方法来接收自定义的值。如

 

  // 半径

    private float radius = 0;

   // 类型

    private int type;

 public RoundImageView(Context context, AttributeSet attrs) {

        this(context, attrs, 0);//没有这个方法就会出错。没有这句话就会读不到值        

    }

 

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {

        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs,  R.styleable.RoundImageView, defStyleAttr, 0);

        radius = typedArray.getDimension(R.styleable.RoundImageView_xhradius, 0);//默认半径0

        type = typedArray.getInt(R.styleable.RoundImageView_xhtype, 0);//默认圆角类型

        typedArray.recycle();

        paint=new Paint();

    }

 

3.在布局文件中引用。并设置属性。


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值