Android自定义View添加自定义属性

前言

前几天阿里的面试官问了我一个问题,如何实现自定义View的自定义属性,我第一感觉是很熟悉,但却答不上来。看来有必要记录一下。

实现

自定义一个View类

这里我举个简单的例子,自定义TextView : MyTextView.java

public class MyTextView extends TextView {
	public MyTextView(Context context) {
		super(context);
	}

	public MyTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

}
复制代码

将自定义的View类放到layout中

仍然很简单

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.attrtest.MyTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="自定义属性" />
</LinearLayout>
复制代码

创建自定义属性

在/res/values/下新建attr.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyTextView">
        <attr name="color" format="color" />
        <attr name="size" format="dimension" />
    </declare-styleable>
</resources>
复制代码

这里有一个域declare-styleable(声明属性),它有一个name属性MyTextView,这个name属性其实就是这个属性在R类中的id。这里有两个attr域,他们都有两个属性,name就不说了,format表示这个属性的类型,目前已知的属性有这些:

reference// 资源类型,通常是@开头,例如@+idxx,@idxx string// 字符串类型,通常是文字信息 dimension// 浮点类型,通常是尺寸度量,单位有很多px,dp,sp等 color// 颜色类型,通常是颜色16进制代码,支持ARGB boolean// 布尔类型,true和false enum// 枚举类型,通常是代表这个属性提供了几种值来进行选择,并且只能选择这几种中的一个 flag// 与enum基本没有区别 integer// 整数类型,通常是整数

在layout中添加自定义属性

public class MyTextView extends TextView {
	public MyTextView(Context context) {
		super(context);
	}

	@SuppressLint("Recycle")
	public MyTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray t = getContext().obtainStyledAttributes(attrs,
				R.styleable.MyTextView);
		int textColor = t.getColor(R.styleable.MyTextView_color, Color.BLACK);
		float textSize = t.getDimension(R.styleable.MyTextView_size, 10);
		this.setTextColor(textColor);
		this.setTextSize(textSize);
	}

	public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}
}
复制代码

使用getContext方法得到当前Context,调用Context.obtainStyledAttributes方法,传入AttributeSet和R.styleable.MyTextView,这里的R.styleable.MyTextView,就是我们在attrs.xml中定义的名称,通过R.styleable来访问。 方法返回一个TypedArray对象。按照attrs,xml中定义的属性的类型,使用不同的get方法获取指定属性的值。

截图

迁移自我的CSDN博客 2015.03.23

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值