android中自定义View设置属性

记录一下,以方便以后用到,再次出错

1.首先需要在values/下面新建一个attrs.xml文件,将一些需要的一些属性填写进去,比如:


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="customTitle">
     <attr name="titleText" format="string"/>   
     <attr name="titleColor" format="color"/>
     <attr name="titleSize" format="dimension"/>
    </declare-styleable> 
    </resources>

2.然后再布局中的xml中,需要填写命名空间,


<RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >


     <com.custom.CustomText01
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        custom:titleText="测试"
        custom:titleColor="#ffff00"
        custom:titleSize="48sp"
        /> 
</RelativeLayout>

3.需要在自定义View的第三个构造函数中,拿到相应的自定义属性


public CustomText01(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);

TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.customTitle);
titleText=array.getString(R.styleable.customTitle_titleText);
color=array.getColor(R.styleable.customTitle_titleColor, 0Xff0000);
size=array.getDimensionPixelSize(R.styleable.customTitle_titleSize,20);

array.recycle();

}

4.重写OnMeasure()方法(可重写,可不重写,视情况而定,有时候设置控件的宽高为wrap时,在屏幕上显示时,会全屏显示,这时候需要重写)

5.OnDraw()方法里面开始绘制.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值