您的位置:首页 > 移动开发 > Android开发

android中自定义View设置属性

2015-09-07 15:54 477 查看
记录一下,以方便以后用到,再次出错

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()方法里面开始绘制.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息