在运行时获取布局高度和宽度android [英] get layout height and width at run time android

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

问题描述

如何获得在 xml 中定义为 fill_parent 的线性布局的宽度和高度?我尝试过 onmeasure 方法,但我不知道为什么它没有给出确切的值.在 oncreate 方法完成之前,我需要在 Activity 中使用这些值.

How can I get width and height of a linear layout which is defined in xml as fill_parent both in height and width? I have tried onmeasure method but I dont know why it is not giving exact value. I need these values in an Activity before oncreate method finishes.

推荐答案

假设我必须获得一个在 XML 中定义的 LinearLayout 宽度.我必须通过 XML 获得它的参考.定义 LinearLayout l 作为实例.

Suppose I have to get a LinearLayout width defined in XML. I have to get reference of it by XML. Define LinearLayout l as instance.

 l = (LinearLayout)findviewbyid(R.id.l1);
ViewTreeObserver observer = l.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                init();
            l.getViewTreeObserver().removeGlobalOnLayoutListener(
                    this);
        }
    });

protected void init() {
        int a= l.getHeight();
            int b = l.getWidth();
Toast.makeText(getActivity,""+a+" "+b,3000).show();
    } 
    callfragment();
}  

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

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