<com.example.selectortest.CustomView android:layout_width="wrap_content" android:layout_height="wrap_content"> </com.example.selectortest.CustomView>
可以發現,我們使用CustomView組件的時候,只是簡單的指明了它的寬度和高度。
現在,假設有這麼一個需要,在之前的矩形組件裡面顯示指定條數的直線。這樣,就需要我們自訂屬性了。
就像在寫程式時,使用一個類型之前需要先定義這個類型一樣。我們需要先在res/values/attrs.xml中定義這種類型。
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="CustomView2"> <attr name="line_numbers" format="integer"></attr> </declare-styleable> </resources>
這樣,我們就可以在xml中指定line_numbers等於多少了。
顯然,直線是由Draw函數畫出來的,我們需要在CustomView類裡面來解析xml,得到直線條數,然後畫出直線。
package com.example.selectortest;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Style;import android.graphics.Rect;import android.util.AttributeSet;import android.view.View;public class CustomView extends View {private Paint mPaint = null;private String mString = "Programmer";private int nLines = 0;public CustomView(Context context, AttributeSet attrs) {super(context, attrs);//解析xml,得到直線條數。TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView2);nLines = a.getInteger(R.styleable.CustomView2_line_numbers, 1);}@Overridepublic void draw(Canvas canvas) {// TODO Auto-generated method stubsuper.draw(canvas);mPaint = new Paint();mPaint.setColor(Color.BLUE);mPaint.setStyle(Style.STROKE);canvas.drawRect(new Rect(10 ,10 ,100 ,100), mPaint);mPaint.setColor(Color.GREEN);mPaint.setTextSize(35.0f);canvas.drawText(mString, 10, 60, mPaint);//畫直線for(int i = 1 ; i <= nLines ;i ++){canvas.drawLine(0, i*10, 200, i*10, mPaint);}}}
使用方法:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom_namespace="http://schemas.android.com/apk/res/com.example.selectortest" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.example.selectortest.CustomView android:layout_width="wrap_content" android:layout_height="wrap_content" custom_namespace:line_numbers="3"> </com.example.selectortest.CustomView> </LinearLayout>
看看效果:
這裡,有一點值得提一下,Style CustomerView2(包含line_numbers屬性)與CustomerView類是沒有關係的,也就是說,Stype CustomerView2可以用來給別的組件賦值,只要那個控制項處理了這個值就行。