Android编程动态创建视图View的方法
在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(25);
- // smooth‘s out the edges of what is being drawn
- paint.setAntiAlias(true);
- }
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- canvas.drawText("Hello World", 5, 30, 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);
- }*/
- static int times = 1;
- /** 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();
- private int i = 0;
- 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(new RectF(60, 120, 260, 320), 0, i, true, vPaint );
- // 弧形角度
- if( (i+=10) > 360 )
- i = 0;
- // 重绘, 再一次执行onDraw 程序
- invalidate();
- }
- }
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。