自定义属性_TypedArray

TypedArray


一般情况下,在设置控件属性时,我们用得时Android系统自带的属性。但有时,我们会自定义一些控件,这些控件需要一些额外的属性。
1. 在项目文件res/value下创建attr.xml文件,该文件中可包含若干个attr集合

<?xml version="1.0" encoding="utf-8">
<resources>
    <declare-styleable name="MyView">
        <attr name="myTextSize" format="dimension"/>
        <attr name="myColor" format="color"/>
    </declare-styleable>
</resources>
解释
resources根标签
declare-styleable name=”MyView”name定义了变量名称
attr name=”myTextSize” format=”dimension”
formate属性类型,dimension表示只能表示字体大小
formate其它属性
reference引用,参考某一资源id
string字符串
color颜色值
dimension尺寸值
boolean布尔值
integer整型值
float浮点值
fraction百分数
enum枚举值
flag位运算

2. 在自定义View的代码中引入自定义属性,修改构造函数

  • context通过调用obtainStyledAttributes方法来获取一个TypeArray,然后由该TypeArray来对属性进行设置
  • obtainStyledAttributes方法有三个,常用obtainStyledAttributes(int[] attrs),其参数直接styleable中获得
  • 调用结束后务必调用recycle()方法,否则这次的设定会对下次的使用造成影响
package com.eyu.attrtextdemo;  

import android.content.Context;  
import android.content.res.TypedArray;  
import android.graphics.Canvas;  
import android.graphics.Paint;  
import android.graphics.Paint.Style;  
import android.util.AttributeSet;  
import android.view.View;  

public class MyView extends View{  
    public Paint paint;  

    public MyView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        paint = new Paint();  

        TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);      
        int textColor = a.getColor(R.styleable.MyView_myColor, 003344);  
        float textSize = a.getDimension(R.styleable.MyView_myTextSize, 33);  
        paint.setTextSize(textSize);  
        paint.setColor(textColor);  
        a.recycle();  
    }  

    public MyView(Context context) {  
        super(context);  
        // TODO Auto-generated constructor stub  
    }  

    @Override
    protected void onDraw(Canvas canvas) {  
        // TODO Auto-generated method stub  
        super.onDraw(canvas);     
        paint.setStyle(Style.FILL);  
        canvas.drawText("aaaaaaa", 10, 50, paint);  
    }        
}  

3.己定义的view的属性中,就可以使用自己在attr中定义的属性啦,例如:

<com.eyu.attrtextdemo.MyView  
        android:layout_height="wrap_content"  
        android:layout_width="wrap_content"  
        myapp:myTextSize="20sp"  
        myapp:myColor="#324243"/>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值