天天看点

Android编程动态创建视图View的方法

在开

发中,在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;  

        paint vpaint = new paint();  

        private int i = 0;  

            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 程序

Android编程动态创建视图View的方法