Sometimes we need to get the width and height of the controls in the activity to do some work, here are three ways to get the width and height:
1. onwindowfocuschanged
@Override publicvoidonWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { int width = image.getMeasuredWidth(); int height = image.getMeasuredHeight(); Toast.makeText(MainActivity.this"width = ""---height = " + height, Toast.LENGTH_SHORT).show(); } }
2. Post mode
@Override protected void onstart () {super . OnStart (); Image.post (new Runnable () { @Override public void r Un () {int width = image.getmeasuredwidth (); int height = image.getmeasuredheight (); Toast.maketext (Mainactivity. This , "Onstart--width =" + width + "---height =" + height, toast.length_short). Show (); } }); }
3. Viewtreeobserver
Viewtreeobserver observer = Image.getviewtreeobserver (); Observer.addongloballayoutlistener (new Ongloballayoutlistener () {
@Override
public
void
ongloballayout () {image.getviewtreeobserver (). Remov Eglobalonlayoutlistener (
this );
int width = image.getmeasuredwidth ();
int height = image.getmeasuredheight (); Toast.maketext (Mainactivity.
This ,
"Onglobal--width =" + width +
"---height ="
+ height, toast.length_short). Show (); } });
Note: The above image is the ImageView control
ImageView image = (ImageView)findViewById(R.id.image);
"Android" gets the width and height of the control