這種文章很多人都不太愿意看嚷那,原因是對于項(xiàng)目上是沒有直接的意義的。而我認(rèn)為,這種文章不僅有利于我們更加深刻的理解某個(gè)知識點(diǎn)戒良,而且還能幫助我們學(xué)習(xí)編程思想和設(shè)計(jì)原理。
1.TypedArray到底有什么作用冠摄?
首先看代碼
<com.example.test.MyTextView
android:layout_width="@dimen/dp100"
android:layout_height="@dimen/dp200"
zhy:testAttr="520"
zhy:text="@string/hello_world" />
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
int count = attrs.getAttributeCount();
for (int i = 0; i < count; i++) {
String attrName = attrs.getAttributeName(i);
String attrVal = attrs.getAttributeValue(i);
Log.e(TAG, "attrName = " + attrName + " , attrVal = " + attrVal);
}
// ==>use typedarray ...
}
輸出如下:
MyTextView(4692): attrName = layout_width , attrVal = @2131165234
MyTextView(4692): attrName = layout_height , attrVal = @2131165235
MyTextView(4692): attrName = text , attrVal = @2131361809
MyTextView(4692): attrName = testAttr , attrVal = 520
/>/>use typedarray
MyTextView(4692): text = Hello world! , textAttr = 520
通過AttributeSet獲取的值糯崎,如果是引用都變成了@+數(shù)字的字符串。 TypedArray其實(shí)是用來簡化我們的工作的河泳。
2.屬性文件中生命的declare-styleable的作用是什么沃呢?
以下是不用styleable的情況~
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="testAttr" format="integer" />
</resources>
package com.example.test;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class MyTextView extends View {
private static final String TAG = MyTextView.class.getSimpleName();
private static final int[] mAttr = { android.R.attr.text, R.attr.testAttr };
private static final int ATTR_ANDROID_TEXT = 0;
private static final int ATTR_TESTATTR = 1;
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// ==>use typedarray
TypedArray ta = context.obtainStyledAttributes(attrs, mAttr);
String text = ta.getString(ATTR_ANDROID_TEXT);
int textAttr = ta.getInteger(ATTR_TESTATTR, -1);
//輸出 text = Hello world! , textAttr = 520
Log.e(TAG, "text = " + text + " , textAttr = " + textAttr);
ta.recycle();
}
}
styleale的出現(xiàn)系統(tǒng)可以為我們完成很多常量(int[]數(shù)組,下標(biāo)常量)等的編寫拆挥,簡化我們的開發(fā)工作(想想如果一堆屬性薄霜,自己編寫常量,你得寫成什么樣的代碼)纸兔。