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是自定義的,可以隨意命名,類似系統(tǒng)默認的命名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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容