自定义MyView在布局中引用
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cheng="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=".MainActivity">
<com.example.myapplication.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
cheng:back="@mipmap/ic_launcher"
cheng:name="我叫什么"
cheng:age="18"
/>
</android.support.constraint.ConstraintLayout>
其中定义的属性在attrs目录下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="back" format="reference|color"></attr>
<attr name="name" format="string"></attr>
<attr name="age" format="integer"></attr>
</declare-styleable>
</resources>
MyView的绘制代码
package com.example.myapplication;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
private Bitmap mBitmap;
private int mAnInt;
private String mString;
public MyView(Context context) {
super(context);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//使用系统工具,获取属性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
for (int i = 0; i < typedArray.getIndexCount(); i++) {
int index = typedArray.getIndex(i);
switch (index){
case R.styleable.MyView_name:
mString = typedArray.getString(index);
break;
case R.styleable.MyView_age:
mAnInt = typedArray.getInt(index, 0);
break;
case R.styleable.MyView_back:
Drawable drawable = typedArray.getDrawable(index);//把BitmapDrawable实例化所以可以强壮
BitmapDrawable bitmapDrawable= (BitmapDrawable) drawable;
mBitmap = bitmapDrawable.getBitmap();
break;
}
}
typedArray.recycle();
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(50);
canvas.drawText(mString+mAnInt,80,80,paint);
canvas.drawBitmap(mBitmap,40,40,paint);
}
}