var值从外部引发回调:

时间:2010-07-16 23:44:02

标签: java

Eclipse在回调中的doSomething()arg列表中重新排列width, height, width, height。左边缘有少许红色X;表示:

Multiple markers at this line
 - Cannot refer to a non-final variable height inside an inner class defined in a different 
  method
 - Cannot refer to a non-final variable width inside an inner class defined in a different 
  method
 - Cannot refer to a non-final variable width inside an inner class defined in a different 
  method
 - Cannot refer to a non-final variable height inside an inner class defined in a different 
  method

显然,我不想通过重复getWindowManager().getDefaultDisplay()holder回调内部或doSomething()内部重复获取这些值来浪费周期。

整个片段都属于一个班级。

感谢您的帮助。

  ... 

  Display display = getWindowManager().getDefaultDisplay();   
  int width = display.getWidth();  
  int height = display.getHeight(); 

  ... 

  final GL10 gl = (GL10) eglContext.getGL();  
  final Handler handler = new Handler();  
  SurfaceHolder holder = view.getHolder(); 
  holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);  

  int w = 0; 
  int h = 0; 
  int x = 0; 
  int y = 0; 

  int b[] = new int[w * (y + h)]; 
  int bt[] = new int[w * h]; 
  IntBuffer ib = IntBuffer.wrap(b); 
  ib.position(0); 
  gl.glReadPixels(x, 0, w, y + h, GL10.GL_RGBA,GL10.GL_UNSIGNED_BYTE,ib); 

  ...

  holder.addCallback(new Callback() { 
    private EGLSurface surface;  
    private Runnable painter;  

    @Override  
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {  
      painter = new Runnable() {  
        @Override  
        public void run() {  
          doSomething(width, height, width, height, gl); 
        }  
      };  
      handler.post(painter);  
    }  
  }); //Callback ends. 
} 

private void doSomething(int x, int y, int w, int h, GL10 gl) {  
  // do something  
}

1 个答案:

答案 0 :(得分:2)

最终关键字放在 surfaceChanged(...)方法的宽度高度参数上使 painter Runnable 中的 run()方法可以访问它们,并摆脱编译器错误。

@Override  
public void surfaceChanged(SurfaceHolder holder, int format, final int width, final int height) {  
  painter = new Runnable() {  
    @Override  
    public void run() {  
      doSomething(width, height, width, height, gl); 
    }  
  };  
  handler.post(painter);  
}

在Java 8中可以避免这种情况,因为它会将宽度高度视为有效最终

将Java 8认为是Lambda Expressions的逻辑扩展,可以产生更简洁的代码:

@Override  
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {  
  painter = () -> {  
      doSomething(width, height, width, height, gl);
  };  
  handler.post(painter);  
}