Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get layout height and width in a fragment

Tags:

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?

like image 674
lory105 Avatar asked Jun 05 '13 10:06

lory105


People also ask

How to get height of a fragment android?

getHeight(); mWidth= myLayout. getWidth(); System. out. println("width: "+mWidth+" height: "+mHeight); } });

How do I find the height and width of RelativeLayout in android programmatically?

private int width, height; RelativeLayout rlParent = (RelativeLayout) findViewById(R. id. rlParent); w = rlParent. getWidth(); h = rlParent.


1 Answers

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.

like image 197
Staffan Avatar answered Sep 17 '22 12:09

Staffan