使用adt14,android 虚拟机2.2 的配置 自定义View
package com.view.my;
import com.view.R;
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.util.AttributeSet;
import android.view.View;
public class MyTextView extends View {
private Paint paint;
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
TypedArray typeArray=context.obtainStyledAttributes(attrs,R.styleable.MyView);
int textColor = typeArray.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供默认值,放置未指定
float textSize = typeArray.getDimension(R.styleable.MyView_textSize, 36);
paint.setColor(textColor);
paint.setTextSize(textSize);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
paint.setStyle(Style.FILL); //设置填充
canvas.drawRect(10, 10, 100, 100, paint); //绘制矩形
paint.setColor(Color.BLUE);
canvas.drawText("我是被画出来的", 10, 120, paint);
}
}
value下的testView.xml 的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
</declare-styleable>
</resources>
layout文件main.xml文件最主要
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:my="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<com.view.my.MyTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
my:textColor="#FFFFFFFF"
my:textSize="22dp"
/>
</LinearLayout>
在运行中出现:xmlns:my="http://schemas.android.com/apk/res"没有引入原因是adt升级的时候把包也更新了改成了xmlns:my="http://schemas.android.com/apk/res-auto"
自定义类中的所有类都要初始化,不然你会看到像:Bind #14 的错误