美文网首页Android开发笔记
Android为CustomView在xml中设置属性

Android为CustomView在xml中设置属性

作者: 一个厨子 | 来源:发表于2015-06-05 20:11 被阅读581次

在写自定义的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

相关文章

网友评论

    本文标题:Android为CustomView在xml中设置属性

    本文链接:https://www.haomeiwen.com/subject/qoidqttx.html