Michał Urban Michał Urban - 1 year ago 49
Java Question

getWidth() and getHeight() return 0 value

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);

Bob Bob
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download