自定义控件——自定义属性

当我们自定义组件时,除了可以使用android系统为我们提供好的属性之外,还可以自定义属性。自定义属性主要步骤如下:

     第一步:

      在res/values目录下新建attrs.xml文件,然后在attrs.xml文件中声明属性。

      例如:

      这里我们定义了3个自定义属性maxRow,maxColumn和orientation。

     Android支持如下10种属性:

     

     第二步:

在使用控件的布局文件中先声明自定义属性xmlns:androidshuai="http://schemas.android.com/apk/res-auto"

然后给自定义属性赋值其中androidshuai可以取任意名字

      例:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:androidshuai="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="#ffffff">


<com.customviewtest.views.MyView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  androidshuai:maxRow="2"
          androidshuai:orientation="vertical" />

</LinearLayout>

     第四步:

      在自定义控件MyView的public MyView (Context context, AttributeSet attrs)的构造函数中获取自定义属性:

         

maxRow,maxColumn,mOrientation都是成员变量。

  

      

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值