Android为CustomView在xml中设置属性


在写自定义的view时,有时想要某些属性像设置宽高一样在xml中设置。How to do?
Step:

自定义View:YourCustomViewName.java

  • 1.在src下的attrs.xml文件中:()
     <declare-styleable name="YourCustomViewName">
      <attr name="time_type" format="enum">
          <enum name="month" value="2"/>
          <enum name="day_of_year" value="6"/>
      </attr>
      <attr name="time" format="integer"/>
    </declare-styleable>

注意:要在<attr/>中使用enum,要在view里定义,在YourCustomViewName.java 里。

  private enum TimeType {month, day_of_year}
  • 2.在引用customView的xml布局文件中:

    1. 在布局文件中加入:
      其中app是自定义的,可以随意命名,类似系统默认的命名Android一样
      xmlns: android="http://schemas.android.com/apk/res/android"

      xmlns:app="http://schemas.android.com/apk/res-auto"
    2. 在自定义的view中,

      <your.package.name.YourCustomViewName
        android:id="@+id/show_time_view"
        android:layout_width="match_parent"
        android:layout_height="75dp"
        app:time="2"
        app:time_type="month"/>
  • 3.在java code中获取xml中设置好的属性:
    在有AttributeSet参数的构造方法中获得你想要的参数

    private void initViewParams(AttributeSet attrs) {
      TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.YourCustomViewName);
      int time = a.getInteger(R.styleable.YourCustomViewName_time, DEFAULT_TIME);
      //后面一个常量是自己设置的默认值
      int type = a.getInteger(R.styleable.YourCustomViewName_time_type, DEFAULT_TIME_TYPE);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值