MyTextView中的代码:
package com.myapplication.customview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by Administrator on 2016/2/25.
*/
public class MyTextView extends View {
private Paint paint = new Paint();
private String string;
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
//拿到布局文件里面的属性的集合
TypedArray typedArray =
context.obtainStyledAttributes(attrs, R.styleable.MyCustomViewAttrs);
//遍历集合,取出自定义每个属性
for (int i = 0; i < typedArray.length(); i++) {
//遍历属性的时候,根据不同属性情况分别对应处理
int arrt = typedArray.getIndex(i);
switch (arrt) {
case R.styleable.MyCustomViewAttrs_content:
string = typedArray.getString(arrt);
setPaint();//设置画笔属性,随后系统会调用onDraw();
break;
default:
break;
}
}
}
//设置画笔的各种属性
private void setPaint() {
paint.setAntiAlias(true);//设置抗锯齿,使线条平滑
paint.setColor(Color.RED);//设置画笔颜色,绿色
paint.setStrokeWidth(2);//设置线条的粗细
paint.setStyle(Paint.Style.STROKE);//设置填充风格
paint.setTextSize(50);//设置字体大小
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* 1,需要设置的属性的内容,相当于setText()的参数。
* 2,3,分别是xy坐标
* 4,画笔,携带了好多属性
*/
canvas.drawText(string, 50f, 100f, paint);
}
}
布局文件需要用到自定义view的属性:
1,自定义view的包名类名全称(获取包名类名全称步骤:java文件右键->copy Reference)
2,根布局中申明引用自定义的属性,本案例中为xmlns:custom=”http://schemas.android.com/apk/res-auto”(步骤:①拷贝xmlns:android=”http://schemas.android.com/apk/res/android”②然后修改了android,自己随意重命名,如custom,③结尾处把apk/res/android修改为apk/res-auto)
3,在自定义view中通过已经申明过的custom设置属性。
参考下图
布局文件中的代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.myapplication.customview.MainActivity"
>
<com.myapplication.customview.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:content="自定义content,模拟text属性"
/>
</RelativeLayout>
效果图: