机器人获得布局的高度和宽度中的片段宽度、机器人、片段、布局

2023-09-06 03:54:41 作者:温柔且固执

我工作的一个片段,我想获得的布局尺寸包含在 XML 片段布局。 当我尝试在code

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();

则返回0。 我需要这些维度来把里面的myLayout其他对象。

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

我尝试使用:

myLayout.getViewTreeObserver().addOnGlobalLayoutListener( 
    new ViewTreeObserver.OnGlobalLayoutListener(){

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

但这code是调用大量的时间,我不知道什么时候是执行。 我需要这些尺寸为公共无效onActivityCreated()方法。可能吗?

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?

推荐答案

每当鉴于小的变化发生了addOnGlobalLayoutListener将被调用。所以,你需要从视图中删除这个监听器。

The addOnGlobalLayoutListener will be called whenever small change of the view happened. So you need to remove this listener from the view.

简单的用法:

public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
if (Build.VERSION.SDK_INT < 16) {
    v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
} else {
    v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}

}

我建议你检查:

if (myLayout.getHeight()>0 && myLayout.getWidth()>0) {
// Do some code...
removeOnGlobalLayoutListener(..)
}