Android Studio下自定义属性的定义和使用
1.自定义属性的定义
在values文件夹下,新建attrs.xml文件,格式内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="com.example.minhuawang.toggleview.ToggleView">
<attr name="switch_background" format="reference"></attr>
<attr name="slide_button_background" format="reference"></attr>
<attr name="state" format="boolean"></attr>
</declare-styleable>
</resources>
2.在布局文件的使用
命名空间的使用,这和eclipse不同
xmlns:exam="http://schemas.android.com/apk/res-auto"
在代码中使用:
String nameSpace = "http://schemas.android.com/apk/res-auto";
布局文件中使用如下:
<com.example.minhuawang.toggleview.ToggleView
android:id="@+id/toggleView"
exam:switch_background="@mipmap/switch_background"
exam:slide_button_background="@mipmap/slide_button"
exam:state="true"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></com.example.minhuawang.toggleview.ToggleView>
3.在自定义的View中获取在xml中定义好的属性
int switch_background = attrs.getAttributeResourceValue(nameSpace, "switch_background", R.mipmap.ic_launcher);
int slide_button_background = attrs.getAttributeResourceValue(nameSpace, "slide_button_background", R.mipmap.ic_launcher);
boolean state = attrs.getAttributeBooleanValue(nameSpace, "state", false);
4.最后总结下自定义View的步骤和必须重写的函数
android界面绘制流程 * measure(测量) -> layout(布局)->draw(绘制) * 重写与上面的相关方法:onMeasure -> onLayout -> onDraw * View : omMeasure(在这个方法里面指定自己的宽高)-> onDraw(绘制自己的内容) * ViewGroup : onMeasure(指定自己的宽高,子View的宽高) -> onLayout(摆放子View) -> onDraw(绘制内容)