android 自定義View - 自定義屬性

要用到自定義的view,但是自定義view需要重寫構(gòu)造方法,構(gòu)造方法中有TypedArray /AttributeSet,學(xué)習(xí)android到現(xiàn)在感覺仍是一無所知,怎么辦?繼續(xù)學(xué)習(xí)。

TypedArray是什么?
AttributeSet是什么?

TypedArray是一個類型數(shù)組,也是一個十分重要的屬性容器。用于存放各種屬性的資源。是屬性的集合,我們獲取屬性一般就是這個類的.getxxx()方法.
重點是學(xué)習(xí)TypedArray的實例是怎么來的?一般是由context.obtainStyledAttributes這個方法,有4個重載的方法。

TypedArray android.content.Context.obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)

這個方法就是從資源里挑出一些屬性來,按照順序放到TypedArray里,參數(shù)可以控制從哪里挑選屬性,挑選哪些。

參數(shù)set:挑選屬性的出處是AttributeSet。

參數(shù)attrs:這是一個屬性的數(shù)組,只是哪些屬性被挑選出來,在之前看R文件的時候R.styleable.button1就是這樣的數(shù)組,我們可以自己new這樣的數(shù)組,再賦值。

參數(shù)defStyleAttr:挑選屬性的出處是defStyleAttr。

參數(shù)defStyleRes:挑選屬性的出處是defStyleRes。

通過第2個參數(shù)指定獲取一些屬性,獲取到的是一個類似數(shù)組的結(jié)果,它的下標(biāo)就像數(shù)組似的從0開始。在這里我們可以聯(lián)想到之前在attrs.xml文件里定義的declare-styleable節(jié)點,定義這個節(jié)點會在R文件產(chǎn)生一個屬性數(shù)組如button1,還會產(chǎn)生下標(biāo)比如button1_textSize1 = 0,這樣我們可以用R文件里的這兩個屬性來處理獲取屬性的這些操作。當(dāng)然我們也可以new出來int的數(shù)組,下標(biāo)自己寫上去。

【】
AttributeSet 是接收xml中定義的屬性信息,不然xml中定義的屬性信息就無法接收。Attributeset看名字就知道是一個屬性的集合,實際上,它內(nèi)部就是一個XML解析器,幫我們將布局文件中該控件的所有屬性解析出來,并以key-value的兼職對形式維護(hù)起來。其實我們完全可以只用他通過下面的代碼來獲取我們的屬性就行。

//打印AttributeSet中的值
    for (int i = 0; i < attrs.getAttributeCount(); i++) {
        Log.i(TAG, "name:" + attrs.getAttributeName(i) + ",value:" + attrs.getAttributeValue(i));
    }

看看我們打印出來的結(jié)果

 com.qianmo.activitydetail I/MyTextView: getWidth():1080,getHeight(): 1731
com.qianmo.activitydetail I/MyTextView: name:background,value:#ff00ff00
com.qianmo.activitydetail I/MyTextView: name:layout_width,value:-1
com.qianmo.activitydetail I/MyTextView: name:layout_height,value:-1
com.qianmo.activitydetail I/MyTextView: name:myText,value: I Love You ......I Love You ......
com.qianmo.activitydetail I/MyTextView: name:myTextColor,value:#ffff3399
com.qianmo.activitydetail I/MyTextView: name:myTextSize,value:25.0sp

可以看到使用Attributeset得到的屬性的值是取到的xml文件中的值,而我們想要的textsize的大小,還得想方法將sp去掉才能拿到我們的25.0,這時候我們就需要一個人幫我們來這樣做了,而TypedArray就順勢而生了,我們來看看使用TypedArray得到的數(shù)據(jù)

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView2, defStyleAttr, 0);
    mText = a.getString(R.styleable.MyTextView2_myText);
    mTextColor = a.getColor(R.styleable.MyTextView2_myTextColor, Color.BLACK);
    mTextSize = a.getDimension(R.styleable.MyTextView2_myTextSize, 30f);
    a.recycle();

這樣的數(shù)據(jù)就是我們想要的了。

自己寫完自定義view后再來補充。

【問題點】
———————————————————————————————
1、為什么要使用自定義屬性呢?相當(dāng)于iOS中的自定義view中擴展的屬性嗎?

我們要使用自定義屬性的話首先要我們有這個自定義屬性,那么我們常見的控件Textview的Android:text屬性是怎么來的呢,我們來一起看一下系統(tǒng)的自定義屬性源碼,系統(tǒng)定義的所有屬性我們可以在\sdk\platforms\Android-xx\data\res\values目錄下找到attrs.xml這個文件,這里只找?guī)讉€很常見的view屬性

 <declare-styleable name="View">
<attr name="id" format="reference" />
<attr name="background" format="reference|color" />
<attr name="padding" format="dimension" />
 ...
<attr name="focusable" format="boolean" />
 ...
</declare-styleable>

<declare-styleable name="TextView">
<attr name="text" format="string" localization="suggested" />
<attr name="hint" format="string" />
<attr name="textColor" />
<attr name="textColorHighlight" />
<attr name="textColorHint" />
 ...
</declare-styleable>

<declare-styleable name="ViewGroup_Layout">
<attr name="layout_width" format="dimension">
    <enum name="fill_parent" value="-1" />
    <enum name="match_parent" value="-1" />
    <enum name="wrap_content" value="-2" />
</attr>
<attr name="layout_height" format="dimension">
    <enum name="fill_parent" value="-1" />
    <enum name="match_parent" value="-1" />
    <enum name="wrap_content" value="-2" />
</attr>
</declare-styleable>

<declare-styleable name="LinearLayout_Layout">
<attr name="layout_width" />
<attr name="layout_height" />
<attr name="layout_weight" format="float" />
<attr name="layout_gravity" />
</declare-styleable>

<declare-styleable name="RelativeLayout_Layout">
<attr name="layout_centerInParent" format="boolean" />
<attr name="layout_centerHorizontal" format="boolean" />
<attr name="layout_centerVertical" format="boolean" />
 ...
</declare-styleable>

首先我們知道我們所有的控件都是繼承自view這個類的,所以view類所擁有的屬性我們繼承它的子類是全部都擁有的,而我們父view類卻不能使用子view的特有的屬性,充分的體現(xiàn)了我們的語言的多態(tài)性。再看看我們上面的標(biāo)簽,都有一個共同點,就是<declare-styleable name = "xxxx"> ,然后里面還有一堆的子標(biāo)簽,而這些子標(biāo)簽就表示這是這個XXX類的屬性。但是并不是每個控件都能使用所有屬性,LinearLayout中能使用layout_weight屬性,而RelativeLayout卻不能使用,因為layout_weight是為LinearLayout的LayoutParams定義的。

如果自定義一個view,可以設(shè)自定義view的背景色,view的展示樣式這時候就需要自定義屬性了。

———————————————————————————————
2、怎么自定義屬性

我們根據(jù)上面的源碼我們知道,這兩種的區(qū)別就是attr標(biāo)簽后面帶不帶format屬性,如果帶format的就是在定義屬性,如果不帶format的就是在使用已有的屬性,name的值就是屬性的名字,format是限定當(dāng)前定義的屬性能接受什么值。而系統(tǒng)定義的屬性一般引用都用android:XXX引用,如果我們現(xiàn)在要定義一個text屬性,所以我們可以有兩種定義我們的方式

常規(guī)方式:

<resources>
   <declare-styleable name="MyTextView">
       <attr name=“text" format="string" />
   </declare-styleable>
</resources>

引用系統(tǒng)已經(jīng)定義好的:

<resources>
  <declare-styleable name="MyTextView">
      <attr name=“android:text"/>
  </declare-styleable>
</resources>

為什么這里我們還要引自系統(tǒng)屬性呢,因為我們的MyTextView是繼承的View,而android:text是TextView的特殊屬性,所以這里必須要引用一下。


3、屬性值的類型format

format一共支持11種類型

① reference

  • 屬性定義:

    <declare-styleable name = "MyImageView">
       <attr name = "background" format = "reference" />
    </declare-styleable>
    
  • 屬性使用:

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

② color

  • 屬性定義:

    <attr name = "textColor" format = "color" />
    
  • 屬性使用:

    <TextView android:textColor = "#00FF00" />
    

③boolean

  • 屬性定義:

    <attr name = "focusable" format = "boolean" />
    
  • 屬性使用:

    <Button android:focusable = "true"/>
    

④dimension

  • 屬性定義:

     <attr name = "layout_width" format = "dimension" />
    
  • 屬性使用:

      <Button android:layout_width = "42dip"/>
    

⑤float

  • 屬性定義:

     <attr name = "fromAlpha" format = "float" />
    
  • 屬性使用:

    <alpha android:fromAlpha = "1.0"/
    

⑥integer

  • 屬性定義:

    <attr name = "framesCount" format="integer" />
    
  • 屬性使用:

    <animated-rotate android:framesCount = "12"/>
    

⑦string

  • 屬性定義:

     <attr name = "text" format = "string" />
    
  • 屬性使用:

    <TextView android:text = "我是文本"/>
    

⑧fraction

  • 屬性定義:

    <attr name = "pivotX" format = "fraction" />
    
  • 屬性使用:

    <rotate android:pivotX = "200%"/>
    

⑨ enum:枚舉值

  • 屬性定義:

    <declare-styleable name="名稱">
       <attr name="orientation">
           <enum name="horizontal" value="0" />
           <enum name="vertical" value="1" />
       </attr>
    </declare-styleable>
    
  • 屬性使用:

    <LinearLayout  
        android:orientation = "vertical">
    </LinearLayout>
    

注意:當(dāng)使用枚舉屬性的話不能在一個屬性中同時使用兩個值

⑩ flag:位或運算

  • 屬性定義:

       <declare-styleable name="名稱">
           <attr name="gravity">
               <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>
      </declare-styleable>
    
  • 屬性使用:

      <TextView android:gravity="bottom|left"/>
    

位運算符在使用的時候可以使用多個屬性

?混合類型:屬性定義時可以指定多種類型值

  • 屬性定義:

     <declare-styleable name = "名稱">
          <attr name = "background" format = "reference|color" />
    </declare-styleable>
    
  • 屬性使用:

     <ImageView android:background = "@drawable/圖片ID" />
      //或者:
     <ImageView  android:background = "#00FF00" />
    

以上就是所有的自定義屬性的格式了,知道了這些,以后方便我們更準(zhǔn)確的去定義自己的屬性


4、 在類中獲取對應(yīng)的自定義屬性

首先在attrs文件中添加我們的自定義屬性

   <?xml version="1.0" encoding="utf-8"?>
     <resources>
       <declare-styleable name="MyTextView2">
          <attr name="myText" format="string"/>
          <attr name="myTextColor" format="color"/>
          <attr name="myTextSize" format="dimension"/>
       </declare-styleable>
    </resources>

然后我們在布局文件中添加我們的自定義屬性,這里要注意一下要引入我們的自定義空間,一般來說有兩種:xmlns:mytextview="http://schemas.android.com/apk/res-auto”,res-auto表示自動查找,還有一種寫法xmlns:mytextview="http://schemas.android.com/apk/com.example.myview",com.example.myview 為我們的應(yīng)用程序包名。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:myview="http://schemas.android.com/apk/res-auto"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
> 
<com.qianmo.activitydetail.MyTextView2
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00"
    myview:myText=" I Love You ......I Love You ......"
    myview:myTextColor="#ff3399"
    myview:myTextSize="25sp"
    />

</LinearLayout>

在構(gòu)造方法中獲取我們的自定義屬性

public MyTextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
   super(context, attrs, defStyleAttr);
   init(context, attrs, defStyleAttr);
  }

   /**
    * 初始化數(shù)據(jù)
  */
  private void init(Context context, AttributeSet attrs, int defStyleAttr) {
   //獲取自定義屬性的值
   TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView2, defStyleAttr, 0);
   mText = a.getString(R.styleable.MyTextView2_myText);
   mTextColor = a.getColor(R.styleable.MyTextView2_myTextColor, Color.BLACK);
   mTextSize = a.getDimension(R.styleable.MyTextView2_myTextSize, 30f);
   a.recycle();

   //初始化Paint數(shù)據(jù)
   mPaint = new Paint();
   mPaint.setColor(mTextColor);
   mPaint.setTextSize(mTextSize);

   //獲取繪制的寬高
   mBound = new Rect();
   mPaint.getTextBounds(mText, 0, mText.length(), mBound);
   Log.i(TAG, "mText :" + mText + ",mTextColor:" + mTextColor+ ",mTextSize:" + mTextSize);
 }

以上只是自定義view基礎(chǔ)

參考:
https://blog.csdn.net/bingospunky/article/details/39890053
https://www.cnblogs.com/wjtaigwh/p/6594680.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,363評論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,497評論 3 416
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,305評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,962評論 1 311
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,727評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,193評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,257評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,411評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,945評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,777評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,978評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,519評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,216評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,657評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,960評論 2 373

推薦閱讀更多精彩內(nèi)容