Android get layout height and width in a fragment

I am working on a fragment and I want to get the dimension of a

layout

contained in the

xml

fragment layout

.
When I try the code

 
 
RelativeLayout myLayout = view.findViewById(R.id.myLayout); myLayout.getHeight();

it returns 0.
I need these dimensions to put inside myLayout other objects.

I try to use:

 
 
myLayout.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener(){ @Override public void onGlobalLayout() { mHeight = myLayout.getHeight(); mWidth= myLayout.getWidth(); System.out.println("width: "+mWidth+" height: "+mHeight); } });

but this code is invoke a lot of time and I don’t know exactly when it is execute.
I need these dimensions into

public void onActivityCreated ()

method. Is it possible?

 

Answer

In onActivityCreated, the view hasn’t been measured yet. So no, you can’t get the measurements from there. onGlobalLayout is a good place to do it. Layouts happen directly after measurement. You can remove your listener afterwards, if you only want to do it once. Note that layouts can change size though (soft keyboards appearing, for example)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值