前言
前几天阿里的面试官问了我一个问题,如何实现自定义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方法获取指定属性的值。
截图
![](https://img.haomeiwen.com/i1397528/5fab6f03b00f6643.png)
迁移自我的CSDN博客
2015.03.23
网友评论