Android自定义属性操作

  • 在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="提示更新" -----<这里是不能使用的!!!>
        />
  • 然后就是在自定义的view中使用定义的属性
 public SettingView(Context context, AttributeSet attrs) {
        super(context, attrs);
       //通过属性得到xml文件中定义的内容,然后使用!
       //这是获取字符串类型的
        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)的值,  和boolean类型 -1默认值
 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);
  • 自己的理解不对的地方可以指出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值