typearray和obtainStyledAttribute的作用

通常是在资源文件下创建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
原文地址:https://www.cnblogs.com/zhengtu2015/p/5018582.html