Sometimes we have a demand based on this, when the activity is created, we need to get the width of a view, and then do the appropriate action, but we get the view in the Oncreate,onstart, the value is 0, only because the view of the drawing project is not completed, and dialog or Popupwindow will report an activity in OnCreate. Not running principle is similar.
Here are a few ways to get view width:
The first way: rewrite the onwindowfocuschanged in the activity, when the activity gets to the focus of the view has been completed, can also get the view of the accuracy of the height. The same dialog and Popupwindow can also be popped here, it should be noted that this method will be called many times, when the Hasfocus is true, you can do the appropriate action
@Override public
void Onwindowfocuschanged (Boolean hasfocus) {
super.onwindowfocuschanged (hasfocus);
if (hasfocus) {
System.out.println ("onwindowfocuschanged width="
+ tvtest.getwidth () + "height=" + Tvtest.getheight ());
}
The second way:
/**
* will perform multiple
times
/private void GetSize1 () {
Viewtreeobserver vto = Tvtest.getviewtreeobserver ();
Vto.addonpredrawlistener (New Viewtreeobserver.onpredrawlistener () {
@Override public
boolean Onpredraw () {
int height = tvtest.getmeasuredheight ();
int width = tvtest.getmeasuredwidth ();
System.out.println ("height" + height);
System.out.println ("width" + width);
return true;}}
);
The Third Way:
private void GetSize2 () {
Viewtreeobserver viewtreeobserver = Tvtest.getviewtreeobserver ();
Viewtreeobserver
. Addongloballayoutlistener (New Ongloballayoutlistener () {
@Override public
Void Ongloballayout () {
tvtest.getviewtreeobserver ()
. Removeglobalonlayoutlistener (this);
System.out.println ("Ongloballayout width="
+ tvtest.getwidth () + "height="
+ tvtest.getheight ());
}
);
}
The Fourth Way:
private void GetSize3 () {
tvtest.post (new Runnable () {
@Override public
void Run () {
System.out.println ("postdelayed width=" + tvtest.getwidth ()
+ "height=" + tvtest.getheight ());
}
);
}
The above is Android to get view width of 4 ways, hope to help everyone's study.