在Android开 发中,在Activity中关联视图View是一般使用setContentView方法,该方法一种参数是使用XML资源直接创 建:setContentView (int layoutResID),指定layout中的一个XML的ID即可,这种方法简单。另一个方法是 setContentView(android.view.View),参数是指定一个视图View对象,这种方法可以使用自定义的视图类。
在一些场合中,需要对View进行一些定制处理,比如获取到Canvas进行图像绘制,需要重载View::onDraw方法,这时需要对View
进行派生一个类,重载所需要的方法,然后使用setContentView(android.view.View)与Activity进行关联,具体代码
举例如下:
- public class temp extends Activity {
- /** 在Activity中关联视图view */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(new DrawView(this));
- }
- /*自定义类*/
- private class DrawView extends View {
- private Paint paint;
- /**
- * Constructor
- */
- public DrawView(Context context) {
- super(context);
- paint = new Paint();
- // set's the paint's colour
- paint.setColor(Color.GREEN);
- // set's paint's text size
- paint.setTextSize();
- // smooth's out the edges of what is being drawn
- paint.setAntiAlias(true);
- }
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- canvas.drawText(, , paint);
- // if the view is visible onDraw will be called at some point in the
- // future
- invalidate();
- }
- }
- }
第二个例子,动态绘图
- public class MyAndroidProjectActivity extends Activity {
- /** Called when the activity is first created. */
- /*
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }*/
- ;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(new DrawView(this));
- }
- private class DrawView extends View {
- Paint vPaint = new Paint();
- ;
- public DrawView(Context context) {
- super(context);
- }
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- System.out.println("this run " + (times++) +" times!");
- // 设定绘图样式
- vPaint.setColor( 0xff00ffff ); //画笔颜色
- vPaint.setAntiAlias( true ); //反锯齿
- vPaint.setStyle( Paint.Style.STROKE );
- // 绘制一个弧形
- canvas.drawArc(, , , ), , i, true, vPaint );
- // 弧形角度
- ) > )
- i = ;
- // 重绘, 再一次执行onDraw 程序
- invalidate();
- }
- }
- }