view.getRootView()的官方解释就是:Finds the topmost view in the current view hierarchy.寻找当前的view层次中处在最顶层的view

我的理解就是找出该view实例所在的view层次的根view。


为证实这个view.getRootView()的真正含义,下面我做了测试:

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:orientation="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());}}

打印结果:



从打印结果我们需要注意的是testBtn、testBtn2虽然id相同,但却是不同的实例,它们所在的view层次也不一样,因此它们通过getRootView得到的根view是不一样的。


最后我们可以看出来,要想获得当前界面所用的xml文件的根view,就可以用

View rootView = ((ViewGroup) (getWindow().getDecorView().findViewById(android.R.id.content))).getChildAt(0);

来获取。

更多相关文章

  1. Activity、Task、应用和进程
  2. react-native开发实例之android发布签名包
  3. 转载:Sensor传感器源码的阅读与应用开发简单实例
  4. android killer插入log打印加密字符串
  5. Android动画特效实例
  6. 打印android key的信息
  7. Android(安卓)activity四种启动模式完全解析
  8. android欢迎界面的编程实现[手相评分-软件实例]
  9. Android中定义全局变量

随机推荐

  1. Android 多媒体应用——MediaPlayer与Sur
  2. Android 如何有效修改包名
  3. android studio 编译打包包含jni的sdk需
  4. Android(安卓)HIDL lshal
  5. Android(安卓)Gallery组件详解
  6. Android 屏幕刷新机制:ViewRootImpl、Chor
  7. 解决onConfigurationChanged不被调用
  8. Android DataBinding & MVVM
  9. if(Build.VERSION.SDK_INT>=Build.VERSIO
  10. Android(安卓)Sensor HAL层分析