Android中自定义属性的使用

 自定义属性: 是指定义可以在布局文件的标签中使用的属性。如TextView控件中的Text属性,但是它是由系统提供的,现如今是由我们自己定义。
使用自定义视图属性的好处: 这样就可以通过布局xml的方式给视图对象指定自己定义的任意属性值, 而不是仅仅只能使用系统中内定的属性啦。
属性值的类型(format)有如下几种:

             1、reference 引用类型值 : @id/...
             2、 color 颜色类型值     #ff00ff
             3、 boolean 布尔类型值    true , false
             4、 dimension 尺寸类型值     dp / px /sp
             5、 integer 整数类型值       weight  progress max
             6、float 浮点型值        0.1f
             7、string 字符串类型值  "atrrs"
             8、<enum> 枚举类型值 :水平/垂直

             9、 flag:位或运算

            10、fraction:百分数

使用步骤:
     一、定义属性: 在values目录下创建attrs.xml

            <declare-styleable name="suibianxue">
                  <attr name="roundColor" format="color"></attr>               
                  <attr name="textColor" format="color"></attr>
                  <attr name="roundWidth" format="dimension"></attr>
                  <attr name="textSize" format="dimension"></attr>
             </declare-styleable>

     二、 在使用了自定义属性的xml布局文件中引用当前应用的命名空间:

                   eclipse中写成:  xmlns:suibianxue="http://schemas.android.com/apk/res/应用包名"  ( 其中suibianxie可以任意写,   )

                  android studio中写成:  xmlns:suibianxue="http://schemas.android.com/apk/res-auto" ( 其中suibianxie可以任意写,  )

    三、 在自定义视图标签中使用自定义属性
           <com.example.customatrrs.MyTextView
                android:id="@+id/mytextview"
                android:layout_width="120dp"
                android:layout_height="120dp"

                suibianxue:roundProgressColor="@android:color/holo_red_dark"
                suibianxue:textColor="@color/text_progress"
                suibianxue:roundWidth="10dp"
                suibianxue:textSize="20sp"  />
 

四、在自定义View类的构造方法中, 取出布局中的自定义属性值
        1、得到所有自定义属性的数组   : TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customatrrs);
           
       2、获取自定义属性的值, 如果没有指定取默认值
                 roundColor = typedArray.getColor(R.styleable.RoundProgress_roundColor, Color.RED);
                  roundProgressColor = typedArray.getColor(R.styleable.RoundProgress_roundProgressColor, Color.GREEN);
                  textColor = typedArray.getColor(R.styleable.RoundProgress_textColor, Color.GREEN);
                  roundWidth = typedArray.getDimension(R.styleable.RoundProgress_roundWidth, UIUtils.dp2px(10));
                 textSize = typedArray.getDimension(R.styleable.RoundProgress_textSize, UIUtils.dp2px(20));

     3、释放资源数据: typedArray.recycle();

 


---------------------
作者:liu_xi_xin
来源:CSDN
原文:https://blog.csdn.net/liu_xi_xin/article/details/54934545
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @   mingruqi  阅读(1825)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示