1. 在values 下定义创建 attrs.xml 自定义标签, 其中name="MyStyle" 用于在代码中得到其属性下面的具体值,详见后面代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyStyle">
<attr name="pwd" format="string"/>
<attr name="mycolor" format="color"/>
</declare-styleable>
</resources>
2. 使用,代码的第三行中,xmls: myffix = "http://schemas.android.com/apk/res-auto", 其中myffix 可自己随意取名,在myffix:pwd, pwd 则是上面定义属性的name
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:myffix="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.uv.br.testdemo.MainActivity5">
<com.uv.br.testdemo.TestView
myffix:pwd="一百块钱不给我"
myffix:mycolor="#ffff674f"
android:textSize="40sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
3. 代码得到自定义标签值
package com.uv.br.testdemo;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by br on 2014/12/1.
*/
public class TestView extends TextView {
public TestView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyStyle);
String pwd = a.getString(R.styleable.MyStyle_pwd);
int color = a.getInteger(R.styleable.MyStyle_mycolor, 0);
setText(pwd);
setTextColor(color);
a.recycle();
}
}