Android get layout height and width in a fragment
Solution 1
There's a cleaner solution to this, just use the View.post()
method on your fragment's root view, and you can call getMeasuredHeight()/getMeasuredWidth()
and get the actual values.
E.g.
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.myfragment, container, false);
root.post(new Runnable() {
@Override
public void run() {
// for instance
int height = root.getMeasuredHeight();
}
});
return root;
}
Very neat and tidy and no messy mucking about with the ViewTreeObserver
.
I've only tested this with android-23 devices, but the API has had this method since level 1.
Anyway, WFM.
Solution 2
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(..)
}
Solution 3
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)
lory105
Updated on June 05, 2020Comments
-
lory105 about 4 years
I am working on a fragment and I want to get the dimension of a
layout
contained in thexml
fragment layout
. When I try the codeRelativeLayout 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? -
Fernando Gallego about 8 yearsI think you can use onViewCreated if you need the measure from the fragment class and not from the activity
-
Minas Mina almost 7 years@FernandoGallego No, in
onViewCreated
width and height return 0. -
funct7 over 2 yearsIs this documented behavior?
-
Staffan over 2 years@funct7 is what documented? That getMeasuredHeight() isn't available until it's visible or View.post?