[Android 自定義 View] 自定義屬性你真的理解嗎?

在這里插入圖片描述

最近本人整理了一些自己的學(xué)習(xí)筆記,內(nèi)容比較零散不適合發(fā)表在博客上,現(xiàn)托管在 GitHub 上歡迎批評(píng)指正

@[toc]

自定義屬性其實(shí)就是一些 xml 標(biāo)簽,他們通過 xml 文件的形式,可以配置某些 View 的信息,讓自定義 View 使用起來更加靈活。

想必很多同學(xué)都已經(jīng)對(duì)于自定義屬性使用的得心應(yīng)手了,但是有一些細(xì)節(jié)你真的知道嗎?比如 AttributeSet、TypedArray 、declare-styleable 這些類和標(biāo)簽的內(nèi)容你都清楚嗎,在獲取自定義屬性的時(shí)候?yàn)槭裁匆?/p>

Context.obtainStyledAttributes(AttributeSet, R.styleable.XXXX);

方法呢?所有的答案都會(huì)在這篇文章里。

必須是 res/values/attrs.xml嗎?

很多文章都說:需要在 res/values 目錄下創(chuàng)建 attrs.xml 文件然后在里面寫我們需要的屬性,其實(shí)這是不太準(zhǔn)確的,通過實(shí)驗(yàn)證明,文件的名字可以隨意指定,不一定必須是 attrs.xml !

[外鏈圖片轉(zhuǎn)存失敗(img-MF8eTbMt-1565511612610)(assets/image-20190809010946000.png)]

例如筆者自定義了一個(gè) custom.xml 文件, 里面的內(nèi)容符合自定義屬性的規(guī)范,在 View 中也是可以正常訪問到的。(具體原因尚不清楚,可能是 Android Stuido 的功能)

文件結(jié)構(gòu)

文件結(jié)構(gòu)
  1. name space : 命名空間,名字可以隨便起,但是最好和自定義 View 的名字相同,因?yàn)?Android Stuido 可以幫我們做一些事情,比如說 command + 手表左鍵,可以直接跳轉(zhuǎn)。

  2. attr name :這就是我們自定義屬性的名字,具體的格式還是模仿 android 內(nèi)部的方式,駝峰式命名或者是 名稱_名稱

  3. format : 屬性的具體類型,此處講解一些特殊的類型,此處不是重點(diǎn),網(wǎng)上文章很多。

    a .reference: 資源id

    <ImageView android:background = "@drawable/圖片ID"/>
    

    b. fraction : 百分?jǐn)?shù)

    • 屬性定義
    <attr name="pivotX" format="fraction"/>
    
    • 使用
    <android:pivotX = "200%"/>
    

    c. flag : 位運(yùn)算,可以在使用過程中指定多個(gè)值

    • 定義
    <attr name="gravity" format="flags">
     <flag name="top" value="0x30"/>
     <flag name="bottom" value="0x50" />
     <flag name="left" value="0x03" />
     <flag name="right" value="0x05" />
     <flag name="center_vertical" value="0x10" />
    </attr>
    
    • 使用
    <TextView android:gravity="bottom|left"/>
    

    d. enum : 枚舉

    • 屬性定義
    <attr name="orientation" format="enum">
     <enum name="horizontal" value="0"/>
     <enum name="vertical" value="1"/>
    </attr>
    

    e. 混合模式 :指定屬性的時(shí)候可以指定多種類型值

     <attr name="background" format="reference|color"/>
    

屬性的使用

  1. 定義屬性
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomAttrsDemo">
        <attr name="text_color" format="color" />
        <attr name="text" format="dimension" />
    </declare-styleable>

</resources>
  1. 在 xml 文件中使用

    在布局文件中使用,首先需要引入命名空間,這樣才能找到我們包中的 attrs,這里我們引入了命名空間 app,res-auto 表示自動(dòng)查找

  xmlns:app="http://schemas.android.com/apk/res-auto"
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.dsd.demo.ui.draw.attrs.CustomAttrsDemo
        android:id="@+id/custom_attrs_demo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        app:text_color="#333333"
        app:text_size="10sp"/>

</FrameLayout>
  1. 在自定義 View 中使用
    此處要注意的是 TypedArray 在使用后一定要調(diào)用 TypedArray.recycler() 方法進(jìn)行回收,否則會(huì)內(nèi)存泄漏。
   /**
    * 自定義屬性 Demo
    *
    * Created by im_dsd on 2019-08-11
    */
   public class CustomAttrsDemo extends android.support.v7.widget.AppCompatTextView {
   
       private final int mTextColor;
       private final int mTextSize;
   
       public CustomAttrsDemo(Context context, AttributeSet attrs) {
           super(context, attrs);
           TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomAttrsDemo);
           mTextColor = array.getColor(R.styleable.CustomAttrsDemo_textColor, Color.BLACK);
           mTextSize = array.getDimensionPixelSize(R.styleable.CustomAttrsDemo_textSize, 18);
           // 注意使用完成之后一定要回收
           array.recycle();
       }
   }

AttributeSet、TypedArray 、declare-styleable

AttributeSet

A collection of attributes, as found associated with a tag in an XML document. Often you will not want to use this interface directly, instead passing it to {@link android.content.res.Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int) Resources.Theme.obtainStyledAttributes()}

可以看到 AtttirbuteSet 是一個(gè)大的屬性集合,裝載了此 View 所有的屬性,用戶可以通過方法:

 Context.obtainStyledAttributes(AttributeSet, R.styleable.XXXX);

獲取指定的屬性集合(一個(gè)明確的小集合 TypedArray)

TypedArray

TypedArray array = Context.obtainStyledAttributes(AttributeSet, R.styleable.XXXX);

TypedArray里面裝的就是具體的屬性了,我們可以通過 :array.getXXXX 的方法獲取具體的屬性值

注意: 在使用后一定要調(diào)用array.recycle 用于釋放內(nèi)存空間,不然此內(nèi)存空間就被浪費(fèi)了

declare-styleable

此標(biāo)簽的作用就是將屬性分組,在 Context.obtainStyledAttributes 方法中指定需要加載的屬性組

這次自定義屬性就完成了。

總結(jié)

自定義屬性還是很簡單的,但是很多同學(xué)都把加載自定義屬性的過程當(dāng)錯(cuò)了模版代碼背了下來,不明白的其中的道理,在使用過程中還是很難達(dá)到靈活運(yùn)用。

  1. 總的來說,自定義屬性就是為了讓自定義 View 在 xml 文件中更加靈活,讓更多的屬性可以被使用者控制。
  2. 自定義的時(shí)候我們需要在 res/values 文件夾下創(chuàng)建 attrs.xml 文件(文件名稱不是固定的,可以隨意起但是還是叫 attrs.xml 統(tǒng)一使用習(xí)慣的較好)然后在文件中使用 declare-styleable 標(biāo)簽自定義一個(gè)屬性組。
  3. 在 layout.xml 文件中使用的時(shí)候需要引入命名空間
  4. 在具體的自定義 View 使用中,需要使用方法
 TypeArray array = Context.obtainStyledAttributes(AttributeSet, R.styleable.屬性集合名);

獲取指定的屬性集 R.styleable.屬性集合名,然后通過方法:

array.getXXXX(R.styleable.屬性集合名_屬性名, 默認(rèn)值)的方式獲取屬性
array.recyler()

方法獲取屬性值


版權(quán)聲明:禁止一切商業(yè)行為,轉(zhuǎn)載請(qǐng)注明出處 https://blog.csdn.net/qq_23191031/article/details/99201766
作者:代圣達(dá)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容