How to make getHeight() not return 0 before the Draw method?

Asked

Viewed 133 times

2

I have a problem where I need to make a ball appear in the middle of the screen getHeight()/2, the real problem is in the function init() where the value of getHeight() return me 0, which should return me the value of the screen height of my device therefore the ball appears at the top when I draw it...

The question is, How to get getHeight() Value before starting draw() ??

public class GameView extends View implements Runnable {

    private static final int INTERVALO = 10;
    private boolean running = true;
    private Paint paint;
    Ball bola;

    public GameView(Context context) {
        super(context);


        paint = new Paint();
        Thread MinhaThread = new Thread(this);
        MinhaThread.setPriority(Thread.MIN_PRIORITY);
        MinhaThread.start();
        init();
    }

    private void init() {

        bola = new Ball(20,getHeight()/2,5,0,0);  //Ball(x,y,size,forca,speed) x e y sao as coordenadas para desenhar na tela.
        Log.e("daniel","Inicializando "+getHeight()); // <-- aqui me retorna0
    }

    public void draw(Canvas canvas){
        super.draw(canvas);

        canvas.drawColor(Color.rgb(100, 190, 230));
        paint.setColor(Color.GREEN);
        canvas.drawRect(0,getHeight()-25,getWidth(),getHeight(),paint); //desenha o chao

        bola.draw(canvas); //AQUI eu desenho meu objeto no topo da tela, deveria ser no meio
        bola.gravidade();  //simulo a gravidade... nada de importante aqui!
    }

    @Override
    public void run() {
        while(running){
            try{
                Thread.sleep(INTERVALO);
            }catch (Exception e){
                Log.e("ERRO", e.getMessage());
            }

            update();
        }
    }

    private void update() {
        //bola.gravidade();
        //dispara o metodo draw (p/desenhar a tela)
        postInvalidate();
    }

    public void release(){
        running = false;
    }

}

PS: I know I could write to getHeight()/2 within the facility draw() but i really need to do this OUT of the draw method. Is there any possibility of doing this? Thank you all.

1 answer

4


There is a way to take the values of getHeight() correctly, and I usually do so, but using Activity, not within your View:

public class ExampleActivity extends Activity {
    //... Código

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

        View view = findViewById(android.R.id.content);
        //Qualquer forma de pegar o ViewRoot
        //ou uma view que ocupe a tela inteira

        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // Nesse momento a view já esta com o seu layout renderizado.
                // Os métodos getHeight() e getWidth() da view irão retornar valores corretos.
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }

    //... Código
}

The other way inside the View is:

public class GameView extends View implements Runnable {
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // Nesse momento, getWidth() e getHeight() estão com os valores corretos.
    }
}

These are two ways I know to get the size of View out of method draw.

  • Using the second method I put lagura = getWidth(); within the onMeasure() right after the comment and tried to print her inside the init() with the log Log. d("Getwidth()",""+lagura); but still printing 0

  • ah, now it’s working, but it seems it takes a while before this method is called ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.