自定义view的使用

View组件的作用类似于Swing编程中的JPanel,可以在VIew里空白区域上绘制想要的场景。

在Android应用中所有的UI组件都继承VIew组件。

如果我们想在屏幕上绘制三行三列的表格该如何实现呢?实现的结果如下

                                                                         

代码如下所示:

一、MainActivity

public class MainActivity extends Activity {
private View myview;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myview=new myView(this);
		setContentView(myview);//采用自定义View
	}
}

二、自定义View


package com.example.androidview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.View;

public class myView extends View {
	private float width;
	private float height;

	public myView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		System.out.println("执行onSizeChanged");
		width = w / 3f;
		height = h / 3f;
		super.onSizeChanged(w, h, oldw, oldh);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		Paint backround = new Paint();
		backround.setColor(getResources().getColor(R.color.ms_backgroud));
		canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), backround);

		// draw the board
		Paint dark = new Paint();
		dark.setColor(getResources().getColor(R.color.ms_dark));

		Paint hilite = new Paint();
		hilite.setColor(getResources().getColor(R.color.ms_hilite));

		Paint light = new Paint();
		light.setColor(getResources().getColor(R.color.ms_light));

		// draw the minor grid lines
		for (int i = 0; i < 3; i++) {
			canvas.drawLine(0, i * height, getWidth(), i * height, light);
			canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1,
					hilite);
			canvas.drawLine(i * width, 0, i * width, getHeight(), light);
			canvas.drawLine(i * width + 1, 0, i * width + 1, getHeight(),
					hilite);
		}
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值