Android中自定义属性(attrs.xml,TypedArray)的使用【转】

该实例是在自定义View上使用自定义属性的。
先来看看源码:MyView.java

Code:
package com.adnroid.test;

import com.adnroid.test.R;

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

public class MyView extends View {
private Paint myPaint;
private static final String myString = "Welcome to our Zoon!";

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

public MyView(Context context, AttributeSet attr) {
super(context, attr);
myPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attr, R.styleable.myView);//TypedArray是一个数组容器
float textSize = a.getDimension(R.styleable.myView_textSize, 30);//防止在XML文件里没有定义,就加上了默认值30
int textColor = a.getColor(R.styleable.myView_textColor, 0xFFFFFFFF);//同上,这里的属性是:名字_属性名
myPaint.setTextSize(textSize);
myPaint.setColor(textColor);
a.recycle();//我的理解是:返回以前取回的属性,供以后使用。以前取回的可能就是textSize和textColor初始化的那段
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//myPaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStyle(Style.FILL);

canvas.drawRect(new Rect(10,10,100,100), myPaint);
myPaint.setColor(Color.WHITE);
canvas.drawText(myString, 10, 100, myPaint);
}

}
attrs.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myView">
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
</declare-styleable>
</resources>
main.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/apk/res/com.adnroid.test"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<com.adnroid.test.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textSize="10px"
test:textColor="#fff"
/>
</LinearLayout>
最终的效果
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值