【Android随记】-- Android自定义控件效果实现
效果图:
看代码,不难:
- package com.example.test;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.util.AttributeSet;
- import android.util.Log;
- import android.widget.RelativeLayout;
- public class MyLayout extends RelativeLayout {
- String title;
- public MyLayout(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- // TODO Auto-generated constructor stub
- }
- public MyLayout(Context context, AttributeSet attrs) {
- super(context, attrs);
- // TODO Auto-generated constructor stub
- }
- public MyLayout(Context context, String title) {
- super(context);
- // TODO Auto-generated constructor stub
- this.title = title;
- }
- @Override
- protected void dispatchDraw(Canvas canvas) {
- Paint paint = new Paint();
- paint.setColor(Color.BLACK);
- int width = getWidth();
- int height = getHeight();
- int empty = 25;
- Paint paint2 = new Paint();
- paint2.setColor(Color.BLACK);
- paint2.setTextSize(25);
- paint2.setAntiAlias(true);
- canvas.drawColor(Color.WHITE);
- float length=paint2.measureText(title);
- Log.e("length", length+"");
- canvas.drawText(title, empty*2, empty+10, paint2);
- canvas.drawLine(empty, empty, empty*2, empty, paint);
- canvas.drawLine(empty*2+length, empty, width - empty, empty, paint);
- // canvas.drawLine(empty, empty, width - empty, empty, paint);
- canvas.drawLine(width - empty, empty, width - empty, height - empty,
- paint);
- canvas.drawLine(width - empty, height - empty, empty, height - empty,
- paint);
- canvas.drawLine(empty, empty, empty, height - empty, paint);
- setPadding(empty+10, empty+10, empty+10, empty+10);
- super.dispatchDraw(canvas);
- }
- }
调用方法:
- MyLayout layout = new MyLayout(this,"測試一下");
- TextView textView=new TextView(this);
转载于:https://blog.51cto.com/gejw0623/1046924