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);
}
}
}