Android 自定义控件xml设置属性

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

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()方法里面开始绘制.

posted @ 2017-07-05 09:41  jxiaow  阅读(194)  评论(0编辑  收藏  举报