我在这里阅读了许多线程,讨论了如何在运行时获得视图大小,但没有任何解决方案对我有用。
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);
}
游戏视图是扩展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()
导致应用程序崩溃。
我知道您必须等待视图的布局,但是我已经尝试了所有建议,但是我已经尝试了其他线程的所有建议。
我的主要缺乏理解来自我在自定义类中使用的实施仪的事实,因此我不确定在哪里可以使用getwidth或类似方法。我通常是Android的新手,所以请在您的解决方案中明确。
编辑:
我应该提到我正在使用宽度和高度形成网格以在表面视图中绘制。
编辑2:
请参阅修订的代码。
如果您的表面是全屏幕,则可以获取屏幕尺寸。
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;
}