2017-08-29 36 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

不幸的是,我的視圖並不是全屏。它在屏幕上呈線性佈局 –