關於android 控制項的預設屬性問題
每個控制項都有很多屬性 而對於一些屬性會有其預設值 而這些預設值是哪裡來的?
我們會想到style或者theme 可往往我們使用TextView或者一些常用的控制項的時候並沒有聲明 style屬性 或者theme屬性啊
下面以最常用的TextView來進行分析
我們知道 開發中縮寫的xml 布局檔案 最後都會被解析成為一個對象
勢必會調用構造方法來建立對象
下面我們來看看TextView的構造方法
public TextView(Context context) { this(context, null); } public TextView(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.textViewStyle); } @SuppressWarnings("deprecation") public TextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); ..... TypedArray a = context.obtainStyledAttributes( attrs, com.android.internal.R.styleable.TextView, defStyle, 0); ....... }
TextView 共有3個構造方法 android提供的控制項 都會有3個構造方法
第一個構造方法 需要我們傳入一個Context對象 一般用於在代碼中建立對象
而第二三個構造方法 則是在xml解析成對象時調用
當控制項沒有指定style時調用第二個構造方法
指定了style時調用第三個
對於TextView 我們一般不指定style 此時就會調用第二個構造方法
public TextView(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.textViewStyle); }
可以看到這裡調用了第三個構造方法
public TextView(Context context, AttributeSet attrs, int defStyle) {}
分析一下參數:
context 是上下文環境 由系統提供
attrs 是解析xml檔案中 控制項的屬性(id,layout_height等)得來的 可以視為一個容器
defStyle 是第二個建構函式傳進來的
com.android.internal.R.attr.textViewStyle
可以看出這是一個id引用對象 在系統attr.xml檔案中定義
由此可知當我們沒有為控制項指定style時 會使用一個預設style
那麼這個預設style從哪來的啊 我們也並沒有為這個textViewStyle設定值啊 ?
答案是 在activity的theme中指定了textViewStyle
以上就是Textview的預設屬性了
總結:
控制項的預設值在style中指定
當不指定控制項style 會使用預設的style
而預設的style的值則在theme中指定
下面分析
TypedArray a=context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
這個obtainStyledAttributes可以理解為使用attrs 和defStyle 對com.android.internal.R.styleable.TextView中的屬性進行解析
我們知道 attrs是xml布局檔案中控制項指定的屬性值 而defStyle 是style中指定屬性值
而com.android.internal.R.styleable.TextView 是在scheme中即attrs.xml中定義的屬性
所以把attrs 和defStyle的值匹配到com.android.internal.R.styleable.TextView的屬性上
mThumbDrawable = a.getDrawable(R.styleable.Switch_thumb);mTrackDrawable = a.getDrawable(R.styleable.Switch_track);mTextOn = a.getText(R.styleable.Switch_textOn);mTextOff = a.getText(R.styleable.Switch_textOff);
最後通過以上代碼得到屬性值