android 自定义标签的使用

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();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值