標籤:android style blog http ar io color 使用 sp
Android開發中,如果系統提供的View組件不能滿足我們的需求,我們就需要自訂自己的View,此時我們會想可不可以為自訂的View定義屬性呢?答案是肯定的。我們可以定義自己的屬性,然後像系統屬性一樣用在layout布局中。
通過下面3步既可以完成自訂屬性:
第一步:在values檔案夾下的attrs.xml檔案(如果沒有可以收到建立)中定義屬性資源檔
1 <?xml version="1.0" encoding="utf-8"?>2 <resources>3 4 <declare-styleable name="AlphaImageView">5 <attr name="myduration" format="integer"></attr>6 </declare-styleable>7 8 </resources>
其中declare-styleable標籤中定義的是自訂的屬性名稱和屬性值的格式,此處是myduration,值是整型。
第二步:在布局檔案中使用自訂屬性,並為其賦值
1 <RelativeLayout 2 xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:my="http://schemas.android.com/apk/res/com.example.attrrestest" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" >10 11 <com.example.attrrestest.AlphaImageView12 android:id="@+id/imageView1"13 android:layout_width="fill_parent"14 android:layout_height="fill_parent"15 android:src="@drawable/abc_cab_background_top_holo_dark"16 my:myduration="60000" />17 18 </RelativeLayout>
其中第11行是我自訂的一個View(代碼在下面),在這個view中(16行)用到了第一步定義的屬性myduration,並為他賦值為60000。需要注意的是系統屬性的首碼用的是“android:”,而自訂屬性的首碼是“my:”,這個首碼是在第3行需要我們手動引入的:“xmlns:my="http://schemas.android.com/apk/res/com.example.attrrestest”,“http://schemas.android.com/apk/res/”部分是固定不變的,後面加上應用的包名,我這裡的包名是“com.example.attrrestest”。
第三步:在自訂的view中擷取我們定義的屬性值。
1 public class AlphaImageView extends ImageView { 2 int alphaDelta = 0;// 透明度每次改變的大小 3 int curAlpha = 0;// 當前透明度的大小 4 int speed = 300; // 300毫秒改變一次 5 6 Handler mHandler = new Handler() { 7 8 @Override 9 public void handleMessage(Message msg) {10 if (msg.what == 0x123) {11 12 curAlpha += alphaDelta;13 if (curAlpha > 255) {14 curAlpha = 255;15 }16 setAlpha(curAlpha);17 }18 }19 };20 21 public AlphaImageView(Context context, AttributeSet attrs) {22 super(context, attrs);23 TypedArray typedArray = getResources().obtainAttributes(attrs, R.styleable.AlphaImageView);// 擷取自訂的屬性集24 Integer duration = typedArray.getInteger(R.styleable.AlphaImageView_myduration, 1);// 從屬性集中擷取需要的屬性的值,該值由xml賦值25 alphaDelta = 255 * speed / duration;26 27 }28 29 @Override30 protected void onDraw(Canvas canvas) {31 setAlpha(curAlpha);//開始為透明,放在顯示之前執行32 super.onDraw(canvas);33 34 final Timer timer = new Timer();35 timer.schedule(new TimerTask() {36 37 @Override38 public void run() {39 if (curAlpha <= 255) {40 mHandler.sendEmptyMessage(0x123);41 } else {42 timer.cancel();43 }44 45 }46 }, 0, speed);47 }48 49 }
此處我定義了一個view名稱為AlphaImageView 繼承於系統的ImageView,在代碼的23,24行是擷取第二步中我們給自訂屬性賦的值,擷取到值後就可以用來控制view變化了。
Android中的自訂屬性的實現