Android get layout height and width in a fragment

后端 未结 3 628
时光取名叫无心
时光取名叫无心 2020-12-15 05:40

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

3条回答
  •  感情败类
    2020-12-15 06:24

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

    Simple usage:

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

    }

    I would suggest you to check :

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

提交回复
热议问题