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 ?
getHeight(); mWidth= myLayout. getWidth(); System. out. println("width: "+mWidth+" height: "+mHeight); } });
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 .
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.
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() .
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With