您的位置:首页 > 移动开发 > Android开发

自定义视图属性

2016-03-10 14:28 405 查看
1.自定义一个继承View或者View子类的视图类(实现含有AttributeSet的构造函数)

import android.util.AttributeSet;
import android.view.View;

/**
* Created by 小新 on 2016/3/10.
*/
public class MyTextView extends View {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);

}
}


2.编写values/attrs.xml(编写自定义属性)声明两个标签  declare-styleable(name)  和attr(name  format)

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextView">
<attr name="rect_color" format="color"></attr>
</declare-styleable>
</resources>


3.在布局文件中使用自定义的属性(注意前面要加上命名空间 AS下只要输入自定义属性,他会自动提示namespace)

<com.example.myapplication.MyTextView
app:rect_color="#cc99cc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


4.在自定义视图类中的构造方法通过TypeArray获取

public class MyTextView extends View {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyTextView);
int color = typedArray.getColor(R.styleable.MyTextView_rect_color,0x0000ff);
setBackgroundColor(color);
//记得回收资源
typedArray.recycle();
}
}

加深理解

1.AttributeSet可以获取布局文件中定义的所有属性的key和value,但是拿到的是它的ID  而通过TypedArray拿到的是解析后的ID
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android