首先在/res/values文件夹下新建一个attrs.xml文件(这里文件名可随意起,但约定俗成用attrs)
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name = "ViewPagerIndicator">
<attr name = "visible_tab_count" format = "integer"/>
<attr name = "title_text" format = "String"/>
<attr name = "title_color" format = "color"/>
</declare-styleable>
</resources>
在自定义View的初始化过程中取得相关属性,这里以visible_tab_count属性为例。
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ViewPagerIndicator);
mTabVisibleCount = a.getInt(R.styleable.ViewPagerIndicator_visible_tab_count, COUNT_DEFAULT_TAB);
if(mTabVisibleCount<0){
mTabVisibleCount = COUNT_DEFAULT_TAB;
}
a.recycle();
在XML布局文件中使用此自定义属性,首先在根布局中声明命名空间,然后在自定义view中使用该属性
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:zhu = "http://schemas.android.com/apk/res/com.example.viewpagerindicator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<com.example.viewpagerindicator.ViewPagerIndicator
android:layout_width="match_parent"
android:layout_height="40dp"
zhu:visible_tab_count = "4"
android:background="@drawable/editor_titlebar_background"
android:orientation="horizontal"
android:id="@+id/ViewPagerIncator">
</com.example.viewpagerindicator.ViewPagerIndicator>
</LinearLayout>
xmlns:zhu = "http://schemas.android.com/apk/res/com.example.viewpagerindicator"是命名空间,固定的组成格式:http://schemas.android.com/apk/res/+包名
zhu:visible_tab_count = "4" 自定义View使用自定义属性