Android TypedArray的用法

Android TypedArray的用法

在項目中經常會有自定義組件的情況,爲了方便組件可以在多個地方獨立使用,我們最常用的是setXX()方法。
那是否可以在XML佈局文件調用時就可以設備自定義組件的各個屬性呢,這個是可以有的,Android提供了TypedArray。
下面介紹一下TypedArray在項目的實際用法:
1,在attrs.xml文件中定義。
   <?xml version="1.0" encoding="utf-8"?>
   <resources>
   
    <declare-styleable name="styleable_name">
       
        <attr name="attr_name" format="reference|color" />
       
    </declare-styleable>
    <resources>
 
 
2,在自定義組件中調用(在構造函數中調用)。
  
   public CustomizeView(Context context, AttributeSet attrs, int defStyle){
  TypedArray mTypedArray = context.obtainStyledAttributes(attrs,R.styleable.styleable_name);
  int color = mTypedArray.getColor(R.styleable.styleable_name_attr_name, Color.GREEN);
   }

  
3, 在XML文件中調用。

     <package_name.CustomizeView
     xmlns:android_custom = "http://schemas.android.com/apk/res/app_package_name"   
    android:id="@+id/round_progressbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android_custom:attr_name="@color/transparent"
    />
  
   xmlns:android_custom = "http://schemas.android.com/apk/res/app_package_name"這句是必不可少的。android_custom代表調用時的前綴,
   可以自定義名字app_package_name是應用的包名
  也可以xmlns:android_custom = "http://schemas.android.com/apk/res-auto"替換成這樣更加方便。
  
  android_custom:attr_name="@color/transparent"就表示在配置中設定attr_name的值。因爲<attr name="attr_name" format="reference|color" />
  這裏的format="reference|color"表示引用或都color,所以在XML中android_custom:attr_name對應的值也要是color值。

  
以上3個步驟,就完成了對TypedArray的簡單使用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章