Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure view in fragment

I need to know ImageView width and height. Is there a way to measure it in fragment ? In standard Activity I use this :

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    image.getWidth();
    image.getHeight();
}

But where can I use image.getWidth(); and image.getHeight(); in fragment ?

like image 769
slezadav Avatar asked Sep 10 '12 13:09

slezadav


People also ask

How do you find the height of a fragment?

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

Is fragment a view?

Neither. Fragment is a base class. So if you want a Fragment with a View then @Override that method. And then the Fragment can be shown to the user if you use the appropriate fragment transaction from an Activity or nested Fragment .

When onAttach is called?

The Fragment class has two callback methods, onAttach() and onDetach() , that you can override to perform work when either of these events occur. The onAttach() callback is invoked when the fragment has been added to a FragmentManager and is attached to its host activity.

What is create the view of a fragment called?

onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity. onCreate() .


1 Answers

Use the GlobalLayoutListener. You assign the listener to your ImageView in onCreateView() just like you do in that answer in the link. It also is more reliable than onWindowFocusChanged() for the main Activity so I recommend switching strategies.

EDIT

Example:

final View testView = findViewById(R.id.view_id);
ViewTreeObserver vto = testView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    Log.d("TEST", "Height = " + testView.getHeight() + " Width = " + testView.getWidth());
    ViewTreeObserver obs = testView.getViewTreeObserver();
    obs.removeGlobalOnLayoutListener(this);
  }
});
like image 147
DeeV Avatar answered Dec 06 '22 21:12

DeeV