1.在sdk包中找到系统定义属性的模板(D:\ADT\sdk\platforms\android-10\data\res\values\attrs.xml);
2.如果是自定义View,找到<declare-styleable name="View">可以查看系统给View定义属性的模板
3.在res/values文件目录下新建attrs.xml文件,并设置属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 声明一个属性集合,一般name用自定义View的类名 -->
<declare-styleable name="ToggleView">
<!-- name:自定义的属性名;format:为自定义属性的类型 -->
<attr name="my_bg" format="reference" />
<attr name="my_bt" format="reference" />
</declare-styleable>
</resources>
4.在布局文件的自定义view中使用自定义的属性
<!-- 1.重写第一行代码,讲android改成自己定义的名字,将最后的android改成包名 -->
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tbkt="http://schemas.android.com/apk/res/com.abc.toggle"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- 2.添加自定义的属性 -->
<com.abc.toggle.ToggleView
android:layout_width="wrap_content"
tbkt:my_bg="@drawable/switch_background"
tbkt:my_bt="@drawable/slide_button"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
5.在自定义控件中通过自定义属性获取资源
/** 布局文件使用ToggleView调用此构造*/
public ToggleView(Context context, AttributeSet attrs) {
super(context, attrs);
//ta是自定义属性的数组
//attrs:是该控件在布局文件中用到的所有属性
//R.styleable.ToggleView:希望从所有属性中获取的属性(也就是我们自定义的属性my_bg和my_bt)
TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.ToggleView);
//获取指定的my_bg属性
BitmapDrawable bgDrawable = (BitmapDrawable) ta.getDrawable(R.styleable.ToggleView_my_bg);
backBitmap=bgDrawable.getBitmap();
//获取指定的my_bt属性
BitmapDrawable btDrawable = (BitmapDrawable)ta.getDrawable(R.styleable.ToggleView_my_bt);
slide_button=btDrawable.getBitmap();
initView();
}
private void initView() {
// 获取图片,如果自定义属性,就可以不必从资源文件生成了
// backBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.switch_background);
// slide_button = BitmapFactory.decodeResource(getResources(),R.drawable.slide_button);
}