简体   繁体   English

getWidth()和getHeight()返回0值

[英]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? 您好,我在android中创建了个人视图,当我想获取其尺寸时,我总是得到0值,我发现我应该在代码中延迟此操作,我有一个问题可以这样做吗? 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 : 使用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. View的边界由于布局处理而改变时,您将获得一个回调。 So you will get the proper dimensions inside the onLayoutChange callback. 因此,您将在onLayoutChange回调中获得适当的尺寸。 Don't forget the remove the listener after the first callback. 不要忘记在第一个回调之后删除监听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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