如何从Android中的主要活动向SurfaceView传递参数

时间:2017-07-11 07:31:23

标签: android android-activity parameters parameter-passing surfaceview

我需要使用surfaceview绘制线图,所以从Main活动我将在此[link] [1]解决方案之后将2个参数传递给surfaceview

[1]:Passing arguments to SurfaceView via Constructor但是我传递的参数仍然是在surfaceview draw方法中的0,请帮助

MySurfaceView.java:     private int len,theta;

public void setParameter(int length, int angle){
    this.len = length;
    this.theta = angle;
    System.out.println("inside setParameter, len: "+len+" ,theta: "+theta);
}
protected void drawSomething(Canvas canvas) {

    System.out.println("Inside drawSomething() , len: "+len+" ,theta: "+theta);

    canvas.drawColor(Color.WHITE);

} MainActivity.java

MySurfaceView myView = new MySurfaceView(MainActivity.this);
                    myView.setParameter(90,30);
                    myView.invalidate();

值只在setParameter()里面打印而不是在drawSomething()里面,我需要在drawSomething()里面使用那些值,请帮忙 编辑了下面的代码,

public MySurfaceView(Context context) {
    super(context);
    init();
}
private void init(){

    paint = new Paint();
    paint.setColor(Color.BLUE);
    paint.setStrokeWidth(3);
    paint.setStyle(Paint.Style.STROKE);

    surfaceHolder = getHolder();
    surfaceHolder.addCallback(new SurfaceHolder.Callback(){

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            canvas = holder.lockCanvas(null);
            drawSomething(canvas);
            holder.unlockCanvasAndPost(canvas);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder,
                                   int format, int width, int height) {
            // TODO Auto-generated method stub
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub
        }});
}

1 个答案:

答案 0 :(得分:1)

由于在回调中调用drawSomething(canvas),您无法知道它是否会比您的下一个函数setParameter(int, int)提前调用。

如果您希望drawSomething(canvas)的值可用,则必须在MySurfaceView的构造函数中传递它们,或者扩展类SurfaceHolder.Callback并将值传递给它们。< / p>