The official explanation for View.getrootview () is: Finds the topmost view in the current view hierarchy. find the top-most view in the current view hierarchy
My understanding is to find the root view of the view hierarchy where the view instance resides.
To confirm the true meaning of this view.getrootview (), I tested the following:
Activity_main.xml:
<absolutelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_ Parent " android:layout_height=" match_parent "> <include layout=" @layout/test_layout "/>< /absolutelayout>
Test_layout.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" match_parent " android:o rientation= "vertical" > <relativelayout android:layout_width= "wrap_content" android:layout_ height= "Wrap_content" > <button android:id= "@+id/testbtn" android:layout_width= "Match_parent" android:layout_height= "wrap_content"/> </RelativeLayout></LinearLayout>
Mainactivity.java:
public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button testbtn = (button) Findviewbyid (R.ID.TESTBTN); LOG.I ("Testbtn", testbtn.tostring () + "ID:" +testbtn.getid ()); LOG.I ("Testbtn ' s Rootview", Testbtn.getrootview (). toString () + "ID:" +testbtn.getrootview (). GetId ()); View TestView =layoutinflater.from (this). Inflate (r.layout.test_layout, NULL); Button testBtn2 = (button) Testview.findviewbyid (R.ID.TESTBTN); LOG.I ("TestBtn2", testbtn2.tostring () + "ID:" +testbtn2.getid ()); LOG.I ("TestBtn2 ' s Rootview", Testbtn2.getrootview (). toString () + "ID:" +testbtn2.getrootview (). GetId ()); View Decorview = GetWindow (). Getdecorview (); View Contentview =decorview.findviewbyid (android. R.id.content); View Mainrootview = ((ViewGroup) contentview). Getchildat (0); LOG.I ("Decorview", decorview.tostring () + "ID:" +decorview.getid ()); LOG.I ("Contentview", contentview.tostring () + "ID:" +contentview.getid()); LOG.I ("Mainrootview", mainrootview.tostring () + "ID:" +mainrootview.getid ());}}
Printing results:
from the printed results we need to note that testbtn, testBtn2 although the same ID, but it is a different instance, they are located in the same view hierarchy, so they get through the Getrootview root view is not the same.
Finally, we can see that to get the root view of the XML file used by the current interface, you can use the
View Rootview = ((ViewGroup) (GetWindow (). Getdecorview (). Findviewbyid (Android. r.id.content)). Getchildat (0);
To get.
The true meaning and testing of "Android" View.getrootview ()