-1

Hello I've created my personal view in android and when I want to get its dimension I get always 0 value, I've found that I should delay this action in my code, I have one question can I do this in this way? I get good dimension

Personalview myView = (Personalview)findViewById(R.id.myView);
myView.postDelayed(new Runnable() {
    @Override
    public void run() {
        Log.i("WIDTH",String.valueOf(myView .getHeight()));
        Log.i("HEIGHT",String.valueOf(myView .height()));
    }
},1000);
Michał Urban
  • 113
  • 12
  • hard to imagine from so short fragment. what is and where initialised 'snake'. Too short code – Jacek Cz Aug 16 '17 at 16:07
  • Possible duplicate of [getWidth() and getHeight() of View returns 0](https://stackoverflow.com/questions/3591784/getwidth-and-getheight-of-view-returns-0) – Oleg Estekhin Aug 16 '17 at 16:07
  • Possible duplicate of [getHeight returns 0 for all Android UI objects](https://stackoverflow.com/questions/8170915/getheight-returns-0-for-all-android-ui-objects) – Yoni Aug 16 '17 at 16:09

1 Answers1

3

Use OnLayoutChangeListener:

myView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                myView.removeOnLayoutChangeListener(this);

                // get dimensions now
            }
        });

This is a better approach than setting an arbitrary delay. You will get a callback when the bounds of the View changes due to layout processing. So you will get the proper dimensions inside the onLayoutChange callback. Don't forget the remove the listener after the first callback.

Bob
  • 13,447
  • 7
  • 35
  • 45
  • Do not remove the listener on first call. This won't get you the dimension everytime. Occasionally onLayoutChange will be called with 0/0 dimension on first call, but with dimension on second. Remove listener, when measured height/width > 0. – JacksOnF1re Aug 16 '17 at 16:32