以编程方式获取布局的高度和宽度 [英] Get height and width of a layout programmatically

查看:86
本文介绍了以编程方式获取布局的高度和宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计了一种布局,其中LinearLayout有2个子级LinearLayoutFrameLayout,并且在每个子级中我放置不同的视图.

I have designed an layout in which LinearLayout has 2 children LinearLayout and FrameLayout and in each child I put different views.

我只是想测量FrameLayout的高度和宽度,以便能够实现自己的目的.

I just wanted to measure height and width of FrameLayout so that I could serve my purpose.

在程序中,我正在使用

int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getHeight();
width=fr.getWidth();

将两者的值均返回为0

即使我尝试使用以下代码 int高度,宽度;

Even I tried with following code int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getMeasuredHeight();
width=fr.getMeasuredWidth();

返回相同的值0

最后我尝试了以下代码, int高度,宽度;

and finally I tried with following code, int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getgetLayoutParams().height();
width=fr.getLayoutParams().width;

返回我-2-1

我希望解决方案以编程方式获取任何布局的高度和宽度吗?

I want the solution to get height and width of any layout programmatically?

推荐答案

视图本身具有自己的生命周期,基本上如下:

The view itself, has it's own life cycle which is basically as follows:

  • 已附加

  • Attached

已测量

布局

绘制

因此,根据您何时尝试获取宽度/高度,您可能看不到预期的显示,例如,如果您在onCreate期间执行此操作,那么到那时,该视图甚至可能无法测量另一方面,如果您在按钮的onClick方法中执行此操作,则很可能到目前为止,该视图已被附加,度量,布局和绘制,因此,您将看到期望值,应实现一个ViewTreeObserver以确保您在适当的时候获取值.

So, depending on when are you trying to get the width/height you might not see what you expect to see, for example, if you are doing it during onCreate, the view might not even been measured by that time, on the other hand if you do so during onClick method of a button, chances are that by far that view has been attached, measured, layout, and drawn, so, you will see the expected value, you should implement a ViewTreeObserver to make sure you are getting the values at the proper moment.

LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                this.layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight(); 

    } 
});

这篇关于以编程方式获取布局的高度和宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆