Android:以编程方式在XML中具有fill_parent的Layout的宽度 [英] Android: get width of Layout programatically having fill_parent in its xml

查看:145
本文介绍了Android:以编程方式在XML中具有fill_parent的Layout的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LinearLayout,其宽度在xml中设置为fill_parent,现在我需要在运行时以编程方式设置其宽度.所以我做到了:

I have the a LinearLayout with width set in xml as fill_parent , now i need its width at runtime programatically. So i did this:

    LinearLayout layoutGet=(LinearLayout) findViewById(R.id.GameField1);
    LayoutParams layParamsGet= layoutGet.getLayoutParams();
    int width=layParamsGet.width;

但是发现调试中的width值为-1,任何有主意的人为什么我在运行时都无法获得在Layout xml中设置fill_parent的LinearLayout在运行时的确切宽度.

But width value on debugging was found to be -1, anybody with idea why can't i get the exact width at runtime for LinearLayout with fill_parent set in layout xml.

推荐答案

我有一种简单的方法可以工作.

I got a simple approach working.

myLayout = (RelativeLayout) findViewById(R.id.my_layout);
myLayout.post(new Runnable() 
    {

        @Override
        public void run()
        {
            Log.i("TEST", "Layout width : "+ myLayout.getWidth());

        }
    });

下面提到的詹斯·沃斯纳克(Jens Vossnack)的方法很好用.但是,我发现GlobalLayoutListener的onGlobalLayout()方法被重复调用,在某些情况下可能不合适.

Jens Vossnack's approach mentioned below works fine. However, I found that the onGlobalLayout() method of GlobalLayoutListener is called repeatedly, which may not be appropriate in certain cases.

这篇关于Android:以编程方式在XML中具有fill_parent的Layout的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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