自定义view,实现TextView效果,可以设置textColor和textSize
1.MyView.java
package com.example.myview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View{
private Paint paint;
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
//Paint: 画笔 用来画文字或者图形,可以设置颜色等
paint = new Paint();
//TypedArray:用来存储自定义的属性
// R.styleable.MyView:自定义属性的xml文件,一般放在attrs.xml中
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供默认值
float textSize = array.getDimension(R.styleable.MyView_textSize, 12);
paint.setColor(textColor);
paint.setTextSize(textSize);
array.recycle(); //一定要调用
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawText("Hello World", 10, 100, paint);//显示文字,距离左边,距离上边,画笔
}
}
2.activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myview="http://schemas.android.com/apk/res/com.example.myview"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.example.myview.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
myview:textSize = "30sp"
myview:textColor = "#666666"
/>
</RelativeLayout>
3.attrs.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>
<a target=_blank href="http://download.csdn.net/detail/bei741178678/8425129">源码下载 </a>