2013-03-13 3 views
0

У меня есть небольшая проблема, так как показ на этих снимках, я не могу вернуть размер экрана, как я хочу, и я немного потерял ... (Я учусь)Не могу получить обратно размер экрана android

http://imageshack.us/f/708/erreurtaillepong4.png/

http://imageshack.us/f/708/erreurtaillepong5.png/

мне нужно иметь ширину и высоту экрана

Пожалуйста, помогите

EDIT 1

Вот мой код, как спросил:

package com.salocincreations.pong; 

import android.graphics.Canvas; 
import android.graphics.Paint; 
import android.graphics.Rect; 

public class GameState { 

    //Largeur et hauteur de l'écran 
    int _screenWidth = TailleEcran.Measuredwidth; 
    int _screenHeight = TailleEcran.Measuredheight; 


    //La balle 
    final int _ballSize = 10; 
    int _ballX = _screenWidth/2; int _ballY = _screenHeight/2; 
    int _ballVelocityX = 2;  int _ballVelocityY = 4; 

    //Les barres 
    final int _batLength = 75; final int _batHeight = 10; 
    int _topBatX = (_screenWidth/2) - (_batLength/2); 
    final int _topBatY = 10; 
    int _bottomBatX = (_screenWidth/2) - (_batLength/2); 
    final int _bottomBatY = _screenHeight - 20; 

    public GameState() 
    { 
    } 

    //The update method 
    public void update() { 

    _ballX += _ballVelocityX; 
    _ballY += _ballVelocityY; 

    //DEATH! 
    if(_ballY > _bottomBatY + 10 || _ballY < 0)   
    {_ballX = 100; _ballY = 100;}//Collisions with the goals 

    if(_ballX > _screenWidth || _ballX < 0) 
       _ballVelocityX *= -1; //Collisions with the sides  

    if(_ballX > _topBatX && _ballX < _topBatX+_batLength && _ballY - 16 < _topBatY)   
        _ballVelocityY *= -1; //Collisions with the bats  

    if(_ballX > _bottomBatX && _ballX < _bottomBatX+_batLength 
        && _ballY + 16 > _bottomBatY) 
          _ballVelocityY *= -1; 
    } 

    public boolean surfaceTouched(float posX, float posY) { 
     _topBatX = (int) posX; 
     _bottomBatX = (int) posX; 

     return true; 
     } 


    //the draw method 
    public void draw(Canvas canvas, Paint paint) { 

    //Clear the screen 
    canvas.drawRGB(0, 0, 0); 

    //set the colour 
    paint.setARGB(200, 0, 200, 700); 

    //draw the ball 
    canvas.drawRect(new Rect(_ballX,_ballY,_ballX + _ballSize,_ballY + _ballSize), 
           paint); 

    //draw the bats 
    canvas.drawRect(new Rect(_topBatX, _topBatY, _topBatX + _batLength, 
              _topBatY + _batHeight), paint); //top bat 
    canvas.drawRect(new Rect(_bottomBatX, _bottomBatY, _bottomBatX + _batLength, 
              _bottomBatY + _batHeight), paint); //bottom bat 

     // Nous allons dessiner nos points par rapport à la résolution de l'écran 
     int iWidth = canvas.getWidth(); // Largeur 
     int iHeight = canvas.getHeight(); // Hauteur 

     // Affecter une couleur de manière aléatoire 
      paint.setARGB(255, 500, 500, 500); 
      // Définir l'épaisseur du segment 
      paint.setStrokeWidth (2); 
      // Puis dessiner nos points dans le cavenas 
      canvas.drawLine(0, iHeight/2, iWidth, iHeight/2, paint);  
      canvas.drawCircle(iWidth/2, iHeight/2, 50, paint); 
     }    
    } 

и

public class TailleEcran extends Activity { 


    int Measuredwidth; 
    int Measuredheight; 
    Point size = new Point(); 
    WindowManager w = getWindowManager();{ 

     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2){ 
      w.getDefaultDisplay().getSize(size); 

      Measuredwidth = size.x; 
      Measuredheight = size.y; 
      }else{ 
      Display d = w.getDefaultDisplay(); 
      Measuredwidth = d.getWidth(); 
      Measuredheight = d.getHeight(); 
      }}} 

В строках

int _screenWidth = TailleEcran.Measuredwidth; 
int _screenHeight = TailleEcran.Measuredheight; 

ошибки говорит: Не удается сделать статическую ссылку на не- статическое поле TailleEcran.Measuredwidth

и

Не удается сделать статическую ссылку на нестатическое поле TailleEcran.Measuredheight

EDIT 2

Затем anthropomo, я должен написать?

 public class GameState { 
     // declare variables above here without assignments 
     Display display = ((WindowManager) 
      context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
     DisplayMetrics metrics = new DisplayMetrics(); 
     display.getMetrics(metrics); 

     int pixHeight = metrics.heightPixels; 
     int pixWidth = metrics.widthPixels; 
    // dp numbers: 
     float density = context.getResources().getDisplayMetrics().density; 
     float dpHeight = pixHeight/density; 
     float dpWidth = pixWidth/density; 
public GameState(Context context){ 
//all the rest of my class 
    } 

} 
+0

См http://stackoverflow.com/questions/15366712/size-of-the-usable-screen/15367869#15367869 для стандартного способа узнать размер вашего представления. –

+0

Вместо скриншотов вы должны вырезать и вставить соответствующие разделы кода в ваш вопрос. – anthropomo

ответ

0

Попробуйте

Display display = getWindowManager().getDefaultDisplay(); 
Point size = new Point(); 
display.getSize(size); 
int width = size.x; 
int height = size.y; 

На API до 13 вы можете использовать:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth(); // deprecated 
int height = display.getHeight(); // deprecated 
+0

Посмотрите на мою вторую ссылку, я уже в другом классе, но я думаю, что она возвращает 0 – NicMer

+0

И у меня есть несколько ошибок. Http://imageshack.us/f/803/erreurtaillepong6.png/ – NicMer

+0

@NicMer, пожалуйста, вставьте свой код в вашем вопросе. Я попытаюсь его отладить. –

0

Вы можете использовать Context.getResources() и Resources.getDisplayMetrics вроде этого:

DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); 

Тогда вы» 11 га ве

displayMetrics.widthPixels; // width 
displayMetrics.heightPixels; // height 
+0

Мой класс должен расширять для чего? Когда я помещаю «extends Activity», у меня есть несколько ошибок. Http://imageshack.us/f/547/erreurtaillepong7.png/ – NicMer

0

Для совместимости в < 13 и не осуждается:

Display display = ((WindowManager) 
     context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    DisplayMetrics metrics = new DisplayMetrics(); 
    display.getMetrics(metrics); 

    int pixHeight = metrics.heightPixels; 
    int pixWidth = metrics.widthPixels; 
// dp numbers: 
    float density = context.getResources().getDisplayMetrics().density; 
    float dpHeight = pixHeight/density; 
    float dpWidth = pixWidth/density; 

Edit:

Вы получаете ошибки на display.getMetrics(metrics);, потому что только декларации может происходить за пределами методов в классе. Весь этот код должен быть в методе, и если предположить, что GameState не является Activity, этот материал должен быть в конструкторе. Что-то вроде этого:

public class GameState { 
    // declare variables above here without assignments 

    public GameState(Context context){ 
     // everything above, but save the variables outside of the constructor 
    } 

} 

Затем в деятельности, которая использует GameState, сделать gameState = new GameState(this);

+0

У меня слишком много ошибок: «контекст не может быть разрешен» и посмотрите http: // imageshack. us/f/854/erreurtaillepong8.png/ – NicMer

+0

контекст в этом случае был бы «этим», если он в вашей деятельности. – anthropomo

+0

Хорошо, ошибка контекста унаследовала, но все еще есть ошибки в display.getMetrics (метрики); – NicMer

Смежные вопросы