android自定义属性

 

1、自定义属性文件attrs.xml,放入values文件夹中---------attrs.xml

 

<?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>

 

 

2、自定义MyView类此类必须继承View基类 ------MyView.java

 

 

package cn.com.flyfot.attrs;

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

public class MyView extends View {
        private static final String TAG = "MyView"; 
        private Paint mPaint; 
        public MyView(Context context) { 
            super(context); 
        } 
         
        public MyView(Context context, AttributeSet attr) { 
            super(context, attr); 
            mPaint = new Paint(); 
            //获取自定义属性
            TypedArray a = context.obtainStyledAttributes(attr, R.styleable.myView);
            //获取尺寸属性值,默认大小为:30
            float textSize = a.getDimension(R.styleable.myView_textSize, 30);
            //获取颜色属性值,默认颜色为:0x990000FF
            int textColor = a.getColor(R.styleable.myView_textColor, 0x990000FF);
            //设置画笔的尺寸和颜色
            mPaint.setTextSize(textSize); 
            mPaint.setColor(textColor); 
            //缓存属性,可以不设置,主要是为了提高效率
            a.recycle();
        } 
        @Override 
        protected void onDraw(Canvas canvas) { 
            super.onDraw(canvas); 
            canvas.drawRect(new Rect(10 ,10,300,300), mPaint); 
        } 
}

 

3、main.xml文件

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:flyfot="http://schemas.android.com/apk/res/cn.com.flyfot.attrs"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <!-- 设置属性 -->
   <cn.com.flyfot.attrs.MyView
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    flyfot:textSize="120px" 
    flyfot:textColor="#ABCDEFEF" 
    />

 

<!--
    注意引入命名空间:xmlns:flyfot="http://schemas.android.com/apk/res/cn.com.flyfot.attrs"
     -->
  
</LinearLayout>

 

 

备注:

系统在解析main.xml文件时,将实例化MyView类然后当前设置的属性上,就调用onDraw方法画到屏幕上去。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值