Android自定义属性

来源:互联网 发布:神雕侠侣06版源码 编辑:程序博客网 时间:2024/06/05 14:16

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
原创粉丝点击