自定义View最简单的创建

来源:互联网 发布:阿里云设置伪静态 编辑:程序博客网 时间:2024/06/06 10:42

package bawei.com.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
* Created by lenovo on 2017/5/24.
*/

public class MyTextView extends View {
public MyTextView(Context context) {
super(context,null);
}

public MyTextView(Context context, @Nullable AttributeSet attrs) {    super(context, attrs,0);}public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {    super(context, attrs, defStyleAttr);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    super.onMeasure(widthMeasureSpec, heightMeasureSpec);}@Overrideprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {    super.onLayout(changed, left, top, right, bottom);}@Overrideprotected void onDraw(Canvas canvas) {    super.onDraw(canvas);    int measuredHeight = getMeasuredHeight()/2;    int measuredWidth = getMeasuredWidth()/2;    Paint paint = new Paint();    canvas.drawColor(Color.RED);    paint.setColor(Color.BLUE);    paint.setTextSize(20);    paint.setTextAlign(Paint.Align.CENTER);    Paint.FontMetricsInt fm = paint.getFontMetricsInt();    int baseaa=(fm.bottom-fm.top)/2-fm.bottom;    canvas.drawText("类好啊",measuredWidth,measuredHeight+baseaa,paint);}

}
效果图为在屏幕的左上方有一个固定的标题框,然后字体在标题框的中间

原创粉丝点击