android 自定义view(1)

来源:互联网 发布:java语言的变量命名 编辑:程序博客网 时间:2024/06/10 05:50

第一步,在attrs中,新建该view在xml布局文件中所需要的自定义属性

values/attrs.xml<?xml version="1.0" encoding="utf-8"?><resources>    <attr name="titleText" format="string" />    <attr name="titleTextColor" format="color" />    <attr name="titleTextSize" format="dimension" />    <declare-styleable name="CustomTitleView">        <attr name="titleText" />        <attr name="titleTextColor" />        <attr name="titleTextSize" />    </declare-styleable></resources>

第二步,在该view的构造函数中,AttributeSet attrs参数可以获取到布局文件中应用到的所有的属性

public CustomTitleView(Context context, @Nullable AttributeSet attrs) {    }

比如在如下布局中,AttributeSet attrs中包含了layout_width,layout_height,titleText,titleTextColor,titleTextSize等属性及其值。
需要特别注意到的有:
1. 自定义的属性与系统属性的前缀是不同的
2. 自定义的属性的前缀需要声明,如下所示 xmlns:custom=”http://schemas.android.com/apk/res-auto

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:custom="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <self.com.customerview.CustomTitleView        android:layout_width="200dp"        android:layout_height="100dp"        custom:titleText="3712"        custom:titleTextColor="#ff0000"        custom:titleTextSize="40sp" /></RelativeLayout>

在View的构造函数中,获取到这些属性值,重写onDraw,onMeasure。

0 0
原创粉丝点击