Android为CustomView在xml中设置属性

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

自定义View:YourCustomViewName.java

  • 1.在values下的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);
      a.recycle(); 
    }
    

The End

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容