您的位置:首页 > 大数据 > 人工智能

typearray和obtainStyledAttribute的作用

2015-12-04 10:32 585 查看
通常是在资源文件下创建attrs.xml

1.attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="button">
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
根标签要是resources,定义的变量要有个名字,declare-styleable name="button">,这里定义名称为button。在这个名称里,可以有多个自定义属性。定义了个名为textSize的属性,格式是dimension,这个format指定了textSize属性的类型,只能用于定义字体大小。


2.布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.easymorse.textbutton"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@drawable/background_color">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="10dip" />
<LinearLayout android:layout_width="fill_parent"
android:layout_height="40dip">
<com.easymorse.textbutton.TextButton
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:layout_weight="1" android:text="电影"
android:gravity="center_vertical|center_horizontal"
android:background="@drawable/button" android:focusable="true"
android:clickable="true" myapp:textSize="20sp" />

根标签中多了一个 xmlns:myapp
myapp:textSize="20sp"


3.在程序下获取该值

public TextButton(final Context context, AttributeSet attrs) {
this(context, attrs, 0);
TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.button);
this.setTextSize(typedArray.getDimension(R.styleable.button_textSize, 15));
typedArray.recycle();

TypedArray 和obtainStyledAttributes(AttributeSet attrs,R.styleable.button)


4.

这里的自定义属性的format,可以有很多种:

reference
string
color
dimension
boolean
integer
float
fraction
enum
flag
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: