2017-08-29 68 views
1

我在这里阅读了许多线程,讨论如何在运行时获取视图大小,但没有解决方案为我工作。在实现可运行时获取表面视图的高度和宽度

GameScreen.java

public class GameScreen extends AppCompatActivity{ 

// Declare an instance of SnakeView 
GameView snakeView; 

SurfaceHolder surface; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_game_screen); 

    snakeView = (GameView) findViewById(R.id.GameView); 
    surface = snakeView.getHolder(); 

    snakeView = new GameView(this, surface); 

} 

其中GameView是一个视图类延伸surfaceview。以下是我的代码详细说明问题的简化版本。我省略了run()方法和其他许多方法以避免混淆。

GameView.java

public class GameView extends SurfaceView implements Runnable { 

public GameView(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    init(); 
} 

public GameView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    init(); 
} 


public GameView(Context context, SurfaceHolder surfaceholder) { 

    super(context); 
    init(); 

    m_context = context; 

    // Initialize the drawing objects 
    m_Holder = surfaceholder; 
    m_Paint = new Paint(); 
} 

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

     @Override 
     public void surfaceCreated(SurfaceHolder holder) { 

     } 


     @Override 
     public void surfaceChanged(SurfaceHolder holder, 
            int format, int width, int height) { 
     m_Screenheight = height; 
     m_Screenwidth = width; 
     } 

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

但是调用getWidth()getHeight()导致应用程序崩溃。

我知道你必须等待视图的布局,但我已经尝试了所有的建议,但我尝试了其他线程的所有建议都无济于事。

我主要缺乏理解来自于我在自定义类中使用了实现Runnable的事实,所以我不确定在哪里允许使用getWidth或类似的方法。我一般都是新来的android,所以请在你的解决方案中明确。

编辑:

我要指出,我使用的宽度和高度,形成一个网格在surfaceview绘制。

编辑2:

参见修改后的代码。

+0

你有'surfaceChanged()'方法传递你想要的数据 – pskink

+0

所以我应该使用getWidth()在surfaceChanged()? –

+0

'surfaceChanged'需要4个参数,使用它们 – pskink

回答

0

如果你的表面是全屏幕,你可以得到屏幕尺寸。

public GameView(Context context, SurfaceHolder surfaceholder) { 

    super(context); 
    init(); 

    m_context = context; 

    // Initialize the drawing objects 
    m_Holder = surfaceholder; 
    m_Paint = new Paint(); 
    DisplayMetrics displayMetrics = new DisplayMetrics(); 
    ((Activity)context).getWindowManager() 
      .getDefaultDisplay() 
      .getMetrics(displayMetrics); 
    int height = displayMetrics.heightPixels; 
    int width = displayMetrics.widthPixels; 
    m_ScreenHeight= height; 
    m_ScreenWidth= width; 
} 
+0

不幸的是,我的视图并不是全屏。它在屏幕上呈线性布局 –