res/values/attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr format="color" name="textColor"/>
<attr format="dimension" name="textSize"/>
</declare-styleable>
</resources>
src/com/android/spt/MyView.java
package com.android.spt;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View{
private Paint mPaint;
private Context mContext;
private static final String mString = "Welcome to Mi's world";
public MyView(Context context, AttributeSet attrs){
super(context, attrs);
mPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_textColor, 0xFFFFFFFF);
float textSize = a.getDimension(R.styleable.MyView_textSize, 20);
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
a.recycle();
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
mPaint.setStyle(Style.FILL);
canvas.drawRect(new Rect(10,10,100,100),mPaint);
canvas.drawText(mString, 10, 110, mPaint);
}
}
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:spt="http://schemas.android.com/apk/res/com.android.spt"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.android.spt.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
spt:textSize="50px"
spt:textColor="#FF00FF00"
/>
</LinearLayout>
src/com/android/spt
package com.android.spt;
import android.app.Activity;
import android.os.Bundle;
public class MiDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}