Android自定义属性

Android自定义属性

我们在使用自定义组件的组件的时候,经常需要自定义一些额外的属性。那么,下面我们来看看怎么自定义属性。

自定义属性可以分为三步:

  • 第一步:我们需要在res/values/文件夹下面创建一个XML文件attrs.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
         <declare-styleable name="Demo"> 
            <attr name="text" format="string"></attr>  
            <attr name="type" format="integer"></attr>  
            <attr name="textSize" format="dimension"></attr>  
         </declare-styleable>
    </resources>
    

    补充一点:

    1.declear-styleable标签里面的name属性在java代码中变成属性数组的名字
    2.attr标签则是我们自定义的属性,format代表数据类型,它的可选值有string , integer , dimension , reference , color , enum。注意啦,都是小写

  • 第二步: 在我们自定义的控件类的构造方法中获取属性值:

    public DemoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //添加一个视图到该控件
        View view = inflate(context, R.layout.test,null);
        addView(view);
        //获取自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Demo);
    
        String text = typedArray.getString(R.styleable.Demo_text);
        int index = typedArray.getInt(R.styleable.Demo_type, 0);
        float dimension = typedArray.getDimension(R.styleable.Demo_textSize, 12);
        typedArray.recycle();
    
        TextView tv = (TextView) view.findViewById(R.id.tv);
        tv.setText(text);
        tv.setTextSize(dimension);
    }
    

    注意点:在取值完成之后一定要回收

  • 在自定义控件中使用属性

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:myAttrs="http://schemas.android.com/apk/res/com.example.defineattrs"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <com.example.defineattrs.DemoView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            myAttrs:text="自定义的属性"
            myAttrs:type="1"
            myAttrs:textSize="30dp" >
        </com.example.defineattrs.DemoView>
    </RelativeLayout>
    

    注意点:当我们使用自定义属性时,需要添加命名控件xmlns:myAttrs="http://schemas.android.com/apk/res/com.example.defineattrs".这里myAttrs可以随便写,命名空间的最末尾res/后面一段需要改成我们项目对应的包名。用自定义控件时要用全类名。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值