Android开发之attrs.xml

首先在res/valus文件目录下新建attrs.xml文件,用来定义新增的属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="textSize" format="dimension"></attr>
        <attr name="textColor" format="color"></attr>
    </declare-styleable>
</resources>
format是这个值的属于什么类型dimension是属于尺寸,color则是属于颜色


新建TestView.class继承View(这里可以继承任何控件,布局等)

public class TestView extends View{
	Paint mPaint = null;

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

	public TestView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
	}
	

	public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context, attrs);
	}
	
	public void init(Context context, AttributeSet attrs){
		TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyView);   //获取自定义属性,MyView是自定义属性的名称
                                                                                             //可以自己随便定义什么名称
		int color = ta.getColor(R.styleable.MyView_textColor, 0x00000000);   //获取自定义属性文件中的某个自定义属性
		float size = ta.getDimension(R.styleable.MyView_textSize, 28);  //同上
		mPaint = new Paint();
		mPaint.setColor(color);
		mPaint.setTextSize(size);
		ta.recycle();   //据说是为了保存获取的自定义值
	}


	@Override
	public void draw(Canvas canvas) {
		canvas.drawText("哈哈", 60, 60, mPaint);
		super.draw(canvas);
	}
	
	

}
在布局文件中使用:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:test="http://schemas.android.com/apk/res-auto" //xmlns:test="http://schemas.android.com/apk/res/com.huaqiang.testattrs"
    android:layout_width="fill_parent"                   //com.huaqiang.testattrs这是你AndroidManifest.xml文件中的Package路径
    android:layout_height="fill_parent"                  //可以用res-auto来代替,这个会自动寻找
    android:orientation="vertical" >
    
    <com.huaqiang.effect.TestView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        test:textSize="@dimen/big"
        test:textColor="@color/red"/>

</LinearLayout>

这个就能用自己自定义的属性了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值