0

Hello im interested in getting the layouts width and height using android once the layout has been loaded, and then depending on the these measurements to create pictures , textboxes , button with proper dimensions for the Android device that my game runs into ! How is this possible ? in which function should i put the following code :

layout.getWidth();
layout.getHeight();

so it wont return 0 ? It would be a lot more convenient to achieve the above getting the width and height before the form actually loads but from what i have seen this much more difficult Here is my code so far trying to get these measurements :

protected void onStart() {
    super.onStart();
    txt = (TextView) findViewById(R.id.textView);
    img = (ImageView) findViewById(R.id.imageView2);
    layout = (RelativeLayout) findViewById(R.id.MyLayout);
    GameHandler();
}

public void GameHandler()
{
    txt.setText(""+layout.getHeight()) ; //this always returns 0
}

thank you for your help :)

kasf
  • 113
  • 1
  • 2
  • 11

2 Answers2

0

OnGlobalLayoutListener is the best callback to use, I have found so far.

layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
         // This is a async callback. get the view size here.
         txt.setText(""+layout.getHeight()) ;
    }
});

layout has to be a class variable, otherwise you have to use the final modifier.

skipper3k
  • 171
  • 1
  • 1
  • 8
0

Try that

layoutView.post(new Runnable() {

        @Override
        public void run() {
            // Get width and height here
        }
    });
elmorabea
  • 3,243
  • 1
  • 14
  • 20