简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM