安卓自定义属性的使用

来源:互联网 发布:java如何处理高并发 编辑:程序博客网 时间:2024/05/17 23:28

一.前言

自定义属性大家都不陌生,在这里总结一下希望对大家能有帮助.

1.在项目文件res/value下面创建一个attr.xml文件

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="kingtest">        <attr name="animationDuration" format="integer" />        <attr name="testAttr" format="string" />        <attr name="android:text"/>    </declare-styleable></resources>

使用已安卓已有的属性

如上面attr.xml定义的第三个属性,format可以省略

<attr name="android:text"/>

其中format还可以指定其他的类型

  • reference 表示引用,参考某一资源ID
  • string 表示字符串
  • color 表示颜色值
  • dimension 表示尺寸值
  • boolean 表示布尔值
  • integer 表示整型值
  • float 表示浮点值
  • fraction 表示百分数
  • enum 表示枚举值
  • flag 表示位运算

2.布局中定义

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:id="@+id/activity_arc_menu"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@color/colorAccent"    tools:context="com.testdemo.king.kingtestdemo.ArcMenuActivity">    <com.testdemo.king.kingtestdemo.view.ArcMenu        android:layout_marginTop="100dp"        android:layout_marginLeft="50dp"        android:layout_width="200dp"        android:layout_height="200dp"        app:animationDuration="6600"        app:testAttr="自定义属性   app:testAttr"        android:text="安卓原生属性 android:text"       >    </com.testdemo.king.kingtestdemo.view.ArcMenu></RelativeLayout>

3.获取属性值

   public ArcMenu(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.kingtest);        int animationDuration = ta.getInteger(R.styleable.kingtest_animationDuration, -1);        String textAttr = ta.getString(R.styleable.kingtest_testAttr);        String text = ta.getString(R.styleable.kingtest_android_text);        Log.e("king", "animationDuration = " + animationDuration + " , textAttr = " + textAttr+                " , text = " + text);        ta.recycle();    }

调用结束后务必调用recycle()方法,否则这次的设定会对下次的使用造成影响

注意

R.styleable 获取时候要遵循格式 “名称_属性”,本例attr.xml中定义的属性名称为kingtest
即:
获取testAttr属性的值ta.getString(R.styleable.kingtest_testAttr);
而获取安卓原生text属性为R.styleable.kingtest_android_text

4.结果

09-03 08:16:12.158 1445-1445/com.testdemo.king.kingtestdemo E/king: animationDuration = 6600 , textAttr = 自定义属性   app:testAttr , text = 安卓原生属性 android:text

拿到了具体的值就可以按照需求来操作了

原创粉丝点击