- 在AS中创建
- 首先在values 中添加attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SettingView" >
字符串类型
<attr name="des_on" format="string"/>
<attr name="des_off" format="string"/>
<attr name="titleName" format="string"/>
reference引用类型 和boolean类型
<attr name="slide_button" format="reference"/>
<attr name="state" format="boolean"/>
</declare-styleable>
SettingView代表自定义的view,AS中会自动提示,不需要全类名,<而且记住这个属性只能在这个自定义view中使用!!!>
//attr name可以自定义名称,不过有时候可能会显示<你定义的名称已经被占用,这时候需要换个名称>
</resources>
- 然后就是在布局中使用,这里注意需要定义一个命名空间
- xmlns:app=”http://schemas.android.com/apk/res-auto”
- app:这个是自己命名的; res-auto :这个是AS中规定的这样写的…
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.xingao.anquanweishi.ui.SettingView
android:id="@+id/settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:titleName="提示更新"
app:des_on ="打开提示更新"
app:des_off ="关闭提示更新"
app:slide_button="@drawable/slide_button"
app:state="false"
>
<这里app 后面的属性就可以使用之前在attrs.xml文件中定义的属性了>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:titleName="提示更新" -----<这里是不能使用的!!!>
/>
public SettingView(Context context, AttributeSet attrs) {
super(context, attrs);
mTitleName = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "titleName");
mDes_on = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "des_on");
mDes_off = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "des_off");
int slide_button = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res-auto", "slide_button", -1);
boolean state = attrs.getAttributeBooleanValue("http://schemas.android.com/apk/res-auto", "state", false);