淺析Android中如何利用attrs和styles定義控件

一直有個問題就是,Android中是如何通過佈局文件,就能實現控件效果的不同呢?比如在佈局文件中,我設置了一個TextView,給它設置了textColor,它就能夠改變這個TextView的文本的顏色。這是如何做到的呢?我們分3個部分來看這個問題1.attrs.xml  2.styles.xml  3.看組件的源碼。

1.attrs.xml:

 我們知道Android的源碼中有attrs.xml這個文件,這個文件實際上定義了所有的控件的屬性,就是我們在佈局文件中設置的各類屬性

你可以找到attrs.xml這個文件,打開它,全選,右鍵->Show In->OutLine。可以看到整個文件的解構

下面是兩個截圖:

 

 

我們大概可以看出裏面是Android中的各種屬性的聲明,比如textStyle這個屬性是這樣定義的:

Java代碼  收藏代碼
  1. <!-- Default text typeface style. -->  
  2.     <attr name="textStyle">  
  3.         <flag name="normal" value="0" />  
  4.         <flag name="bold" value="1" />  
  5.         <flag name="italic" value="2" />  
  6.     </attr>  

 那麼現在你知道,我們在寫android:textStyle的時候爲什麼會出現normal,bold和italic這3個東西了吧,就是定義在這個地方。

再看看textColor:

Java代碼  收藏代碼
  1. <!-- Color of text (usually same as colorForeground). -->  
  2.     <attr name="textColor" format="reference|color" />  

 format的意思是說:這個textColor可以以兩種方式設置,要麼是關聯一個值,要麼是直接設置一個顏色的RGB值,這個不難理解,因爲我們可以平時也這樣做過。

 

也就是說我們平時在佈局文件中所使用的各類控件的屬性都定義在這裏面,那麼這個文件,除了定義這些屬性外還定義了各種具體的組件,比如TextView,Button,SeekBar等所具有的各種特有的屬性

比如SeekBar:

 

Java代碼  收藏代碼
  1. <declare-styleable name="SeekBar">  
  2.         <!-- Draws the thumb on a seekbar. -->  
  3.         <attr name="thumb" format="reference" />  
  4.         <!-- An offset for the thumb that allows it to extend out of the range of the track. -->  
  5.         <attr name="thumbOffset" format="dimension" />  
  6.     </declare-styleable>  

也許你會問SeekBar的background,等屬性怎麼沒有看到?這是因爲Android中幾乎所有的組件都是從View中繼承下來的,SeekBar自然也不例外,而background這個屬性幾乎每個控件都有,因此被定義到了View中,你可以在declare-styleable:View中找到它。 

 

總結下,也就是說attrs.xml這個文件定義了佈局文件中的各種屬性attr:***,以及每種控件特有的屬性declare-styleable:***

 

2.styles.xml:

剛纔的attrs.xml定義的是組件的屬性,現在要說的style則是針對這些屬性所設置的值,一些默認的值。

 

 

 

這個是SeekBar的樣式,我們可以看到,這裏面設置了一個SeekBar的默認的樣式,即爲attrs.xml文件中的各種屬性設置初始值

Java代碼  收藏代碼
  1. <style name="Widget.SeekBar">  
  2.         <item name="android:indeterminateOnly">false</item>  
  3.         <item name="android:progressDrawable">@android:drawable/progress_horizontal</item>  
  4.         <item name="android:indeterminateDrawable">@android:drawable/progress_horizontal</item>  
  5.         <item name="android:minHeight">20dip</item>  
  6.         <item name="android:maxHeight">20dip</item>  
  7.         <item name="android:thumb">@android:drawable/seek_thumb</item>  
  8.         <item name="android:thumbOffset">8dip</item>  
  9.         <item name="android:focusable">true</item>  
  10.     </style>  

 這個是Button的樣式:

Java代碼  收藏代碼
  1. <style name="Widget.Button">  
  2.         <item name="android:background">@android:drawable/btn_default</item>  
  3.         <item name="android:focusable">true</item>  
  4.         <item name="android:clickable">true</item>  
  5.         <item name="android:textAppearance">?android:attr/textAppearanceSmallInverse</item>  
  6.         <item name="android:textColor">@android:color/primary_text_light</item>  
  7.         <item name="android:gravity">center_vertical|center_horizontal</item>  
  8.     </style>  

 

有了屬性和值,但是這些東西是如何關聯到一起的呢?它們如何被android的framework層所識別呢?

 

3.組件的源碼

我們看下TextView的源碼:

Java代碼  收藏代碼
  1. public TextView(Context context) {  
  2.         this(context, null);  
  3.     }//這個構造器用來給用戶調用,比如new TextView(this);  
  4.   
  5.     public TextView(Context context,  
  6.                     AttributeSet attrs) {  
  7.         this(context, attrs, com.android.internal.R.attr.textViewStyle);  
  8.     }  
  9.   
  10.     public TextView(Context context,  
  11.                     AttributeSet attrs,  
  12.                     int defStyle) {  
  13.         super(context, attrs, defStyle);//爲用戶自定義的TextView設置默認的style  
  14.         mText = "";  
  15.   
  16.         //設置畫筆  
  17.         mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);  
  18.         mTextPaint.density = getResources().getDisplayMetrics().density;  
  19.         mTextPaint.setCompatibilityScaling(  
  20.                 getResources().getCompatibilityInfo().applicationScale);  
  21.          
  22.         mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG);  
  23.         mHighlightPaint.setCompatibilityScaling(  
  24.                 getResources().getCompatibilityInfo().applicationScale);  
  25.   
  26.         mMovement = getDefaultMovementMethod();  
  27.         mTransformation = null;  
  28.   
  29.         //attrs中包含了這個TextView控件在佈局文件中定義的屬性,比如android:background,android:layout_width等  
  30.         //com.android.internal.R.styleable.TextView中包含了TextView中的針對attrs中的屬性的默認的值  
  31.         //也就是說這個地方能夠將佈局文件中設置的屬性獲取出來,保存到一個TypeArray中,爲這個控件初始化各個屬性  
  32.         TypedArray a =  
  33.             context.obtainStyledAttributes(  
  34.                 attrs, com.android.internal.R.styleable.TextView, defStyle, 0);  
  35.   
  36.         int textColorHighlight = 0;  
  37.         ColorStateList textColor = null;  
  38.         ColorStateList textColorHint = null;  
  39.         ColorStateList textColorLink = null;  
  40.         int textSize = 15;  
  41.         int typefaceIndex = -1;  
  42.         int styleIndex = -1;  
  43.   
  44.         /* 
  45.          * Look the appearance up without checking first if it exists because 
  46.          * almost every TextView has one and it greatly simplifies the logic 
  47.          * to be able to parse the appearance first and then let specific tags 
  48.          * for this View override it. 
  49.          */  
  50.         TypedArray appearance = null;  
  51.         //TextView_textAppearance不太瞭解爲什麼要這樣做?難道是爲了設置TextView的一些默認的屬性?  
  52.         int ap = a.getResourceId(com.android.internal.R.styleable.TextView_textAppearance, -1);  
  53.         if (ap != -1) {  
  54.             appearance = context.obtainStyledAttributes(ap,  
  55.                                 com.android.internal.R.styleable.  
  56.                                 TextAppearance);  
  57.         }  
  58.         if (appearance != null) {  
  59.             int n = appearance.getIndexCount();  
  60.             for (int i = 0; i < n; i++) {  
  61.                 int attr = appearance.getIndex(i);  
  62.   
  63.                 switch (attr) {  
  64.                 case com.android.internal.R.styleable.TextAppearance_textColorHighlight:  
  65.                     textColorHighlight = appearance.getColor(attr, textColorHighlight);  
  66.                     break;  
  67.   
  68.                 case com.android.internal.R.styleable.TextAppearance_textColor:  
  69.                     textColor = appearance.getColorStateList(attr);  
  70.                     break;  
  71.   
  72.                 case com.android.internal.R.styleable.TextAppearance_textColorHint:  
  73.                     textColorHint = appearance.getColorStateList(attr);  
  74.                     break;  
  75.   
  76.                 case com.android.internal.R.styleable.TextAppearance_textColorLink:  
  77.                     textColorLink = appearance.getColorStateList(attr);  
  78.                     break;  
  79.   
  80.                 case com.android.internal.R.styleable.TextAppearance_textSize:  
  81.                     textSize = appearance.getDimensionPixelSize(attr, textSize);  
  82.                     break;  
  83.   
  84.                 case com.android.internal.R.styleable.TextAppearance_typeface:  
  85.                     typefaceIndex = appearance.getInt(attr, -1);  
  86.                     break;  
  87.   
  88.                 case com.android.internal.R.styleable.TextAppearance_textStyle:  
  89.                     styleIndex = appearance.getInt(attr, -1);  
  90.                     break;  
  91.                 }  
  92.             }  
  93.   
  94.             appearance.recycle();  
  95.         }  
  96.         //各類屬性  
  97.  boolean editable = getDefaultEditable();  
  98.         CharSequence inputMethod = null;  
  99.         int numeric = 0;  
  100.         CharSequence digits = null;  
  101.         boolean phone = false;  
  102.         boolean autotext = false;  
  103.         int autocap = -1;  
  104.         int buffertype = 0;  
  105.         boolean selectallonfocus = false;  
  106.         Drawable drawableLeft = null, drawableTop = null, drawableRight = null,  
  107.             drawableBottom = null;  
  108.         int drawablePadding = 0;  
  109.         int ellipsize = -1;  
  110.         boolean singleLine = false;  
  111.         int maxlength = -1;  
  112.         CharSequence text = "";  
  113.         CharSequence hint = null;  
  114.         int shadowcolor = 0;  
  115.         float dx = 0, dy = 0, r = 0;  
  116.         boolean password = false;  
  117.         int inputType = EditorInfo.TYPE_NULL;  
  118.   
  119.         int n = a.getIndexCount();  
  120.         for (int i = 0; i < n; i++) {  
  121.             int attr = a.getIndex(i);  
  122.             //通過switch語句將用戶設置的,以及默認的屬性讀取出來並初始化  
  123.             switch (attr) {  
  124.             case com.android.internal.R.styleable.TextView_editable:  
  125.                 editable = a.getBoolean(attr, editable);  
  126.                 break;  
  127.   
  128.             case com.android.internal.R.styleable.TextView_inputMethod:  
  129.                 inputMethod = a.getText(attr);  
  130.                 break;  
  131.   
  132.             case com.android.internal.R.styleable.TextView_numeric:  
  133.                 numeric = a.getInt(attr, numeric);  
  134.                 break;  
  135.   
  136.            //更多的case語句...  
  137.   
  138.            case com.android.internal.R.styleable.TextView_textSize:  
  139.                 textSize = a.getDimensionPixelSize(attr, textSize);//設置當前用戶所設置的字體大小  
  140.                 break;  
  141.   
  142.             case com.android.internal.R.styleable.TextView_typeface:  
  143.                 typefaceIndex = a.getInt(attr, typefaceIndex);  
  144.                 break;  
  145.            //更多的case語句...  
  146. }  

 

通過上面的代碼大概可以知道,每個組件基本都有3個構造器,其中只傳遞一個Context上下文的那個構造器一般用來在java代碼中實例化使用。

比如你可以

Java代碼  收藏代碼
  1. TextView tv = new TextView(context);  

 來實例化一個組件。

 

最終調用的是第3個構造器

Java代碼  收藏代碼
  1. public TextView(Context context,  
  2.                     AttributeSet attrs,  
  3.                     int defStyle)  

 

 在這個構造器中爲你設置了默認的屬性attrs和值styles。關鍵不在這裏,而是後面通過使用下面的代碼

Java代碼  收藏代碼
  1. TypedArray a =  
  2.             context.obtainStyledAttributes(  
  3.                 attrs, com.android.internal.R.styleable.TextView, defStyle, 0);  

 來將屬性和值獲取出來,放到一個TypeArray中,然後再利用一個switch語句將裏面的值取出來。再利用這些值來初始化各個屬性。這個View最終利用這些屬性將這個控件繪製出來。

如果你在佈局文件中定義的一個View的話,那麼你定義的值,會被傳遞給構造器中的attrs和styles。也是利用同樣的方式來獲取出你定義的值,並根據你定義的值來繪製你想要的控件。

再比如其實Button和EditText都是繼承自TextView。看上去兩個控件似乎差異很大,其實不然。Button的源碼其實相比TextView變化的只是style而已:

Java代碼  收藏代碼
  1. public class Button extends TextView {  
  2.     public Button(Context context) {  
  3.         this(context, null);  
  4.     }  
  5.   
  6.     public Button(Context context, AttributeSet attrs) {  
  7.         this(context, attrs, com.android.internal.R.attr.buttonStyle);  
  8.     }  
  9.   
  10.     public Button(Context context, AttributeSet attrs, int defStyle) {  
  11.         super(context, attrs, defStyle);  
  12.     }  
  13. }  

 再看看EditText:

Java代碼  收藏代碼
  1. public class EditText extends TextView {  
  2.     public EditText(Context context) {  
  3.         this(context, null);  
  4.     }  
  5.   
  6.     public EditText(Context context, AttributeSet attrs) {  
  7.         this(context, attrs, com.android.internal.R.attr.editTextStyle);  
  8.     }  
  9.   
  10.     public EditText(Context context, AttributeSet attrs, int defStyle) {  
  11.         super(context, attrs, defStyle);  
  12.     }  
  13.   
  14.     @Override  
  15.     protected boolean getDefaultEditable() {  
  16.         return true;  
  17.     }  
  18.   
  19.     @Override  
  20.     protected MovementMethod getDefaultMovementMethod() {  
  21.         return ArrowKeyMovementMethod.getInstance();  
  22.     }  
  23.   
  24.     @Override  
  25.     public Editable getText() {  
  26.         return (Editable) super.getText();  
  27.     }  
  28.   
  29.     @Override  
  30.     public void setText(CharSequence text, BufferType type) {  
  31.         super.setText(text, BufferType.EDITABLE);  
  32.     }  
  33.   
  34.     /** 
  35.      * Convenience for {@link Selection#setSelection(Spannable, int, int)}. 
  36.      */  
  37.     public void setSelection(int start, int stop) {  
  38.         Selection.setSelection(getText(), start, stop);  
  39.     }  
  40.   
  41.     /** 
  42.      * Convenience for {@link Selection#setSelection(Spannable, int)}. 
  43.      */  
  44.     public void setSelection(int index) {  
  45.         Selection.setSelection(getText(), index);  
  46.     }  
  47.   
  48.     /** 
  49.      * Convenience for {@link Selection#selectAll}. 
  50.      */  
  51.     public void selectAll() {  
  52.         Selection.selectAll(getText());  
  53.     }  
  54.   
  55.     /** 
  56.      * Convenience for {@link Selection#extendSelection}. 
  57.      */  
  58.     public void extendSelection(int index) {  
  59.         Selection.extendSelection(getText(), index);  
  60.     }  
  61.   
  62.     @Override  
  63.     public void setEllipsize(TextUtils.TruncateAt ellipsis) {  
  64.         if (ellipsis == TextUtils.TruncateAt.MARQUEE) {  
  65.             throw new IllegalArgumentException("EditText cannot use the ellipsize mode "  
  66.                     + "TextUtils.TruncateAt.MARQUEE");  
  67.         }  
  68.         super.setEllipsize(ellipsis);  
  69.     }  
  70. }  

 不知道你是不是和我一樣感到意外呢?

 

不得不說這種方式非常的好。最大程度地利用了繼承,並且可以讓控件之間的屬性可以很方便的被開發者使用。也利用以後的擴展,實際上,不同的style就可以得到不同的UI,這也是MVC的一種體現。

比如用戶想自定義某個控件,只要覆蓋父類的style就可以很輕鬆的實現,可以參考我的一篇博文,就是使用style自定義ProgressBar 參考上一篇文章。

http://blog.csdn.net/hlglinglong/article/details/38662427

Android中的主題theme也是使用的style。當用戶在Activity中設置一個style的時候那麼會影響到整個Activity,如果爲Application設置style的話,則會影響所有的Activity,所以,如果你在開發一個應用的時候

可以考慮將應用的Activity的背景顏色等一類的屬性放到一個style中去,在Application中調用,這種做法會比較方便。

themes.xml:

Java代碼  收藏代碼
  1. <!-- Variant of the default (dark) theme with no title bar -->  
  2.     <style name="Theme.NoTitleBar">  
  3.         <item name="android:windowNoTitle">true</item>  
  4.     </style>  
  5.       
  6.     <!-- Variant of the default (dark) theme that has no title bar and  
  7.          fills the entire screen -->  
  8.     <style name="Theme.NoTitleBar.Fullscreen">  
  9.         <item name="android:windowFullscreen">true</item>  
  10.         <item name="android:windowContentOverlay">@null</item>  
  11.     </style>  

 我們平時使用的主題實際上就定義在這個文件中。也是一個style。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章