美文网首页
四、DecorView 的结构图

四、DecorView 的结构图

作者: HungerDeng | 来源:发表于2018-09-18 21:50 被阅读0次
    DecorView 的结构图

    1. 当某个 View 添加到布局中后

    //得到 DecorView, DecorView是 FrameLayout 
    ViewGroup decorView = view.getRootView(); //这里的View是被添加到页面中的View
    ViewGroup decorView = getWindow().getDecorView();
    
    //得到Content, content是 FrameLayout 
    ViewGroup content = decorView.findViewById(android.R.id.content);
    
    //得到我们自己设置的布局,可能是 各种各样的ViewGroup,也可能是一个View
    ViewGroup layout = content.getChildAt(0);
    

    2. 当某个 View 未添加到布局中

    值得注意的是,如果一个View并没有添加到布局中显示出来, view.getRootView()得到的是它最顶层的布局(XML的根布局),而不是 DecorView. 例如

    //example.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/rootView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize" />
      
            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1" >
                <TextView
                    android:id="@+id/text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" /> 
            </FrameLayout>
    
        </LinearLayout>
    </RelativeLayout >
    
    
    //java
    final View view = View.inflate(this, R.layout.example, null);
    final RelativeLayout rootView=view.findViewById(R.id.rootView);
    final TextView tv=view.findViewById(R.id.text);
    //View在代码中通过View.inflate实例化,没有添加到显示界面前
    System.out.println(" tv的根视图 RelativeLayout 的Id =" + rootView.getId());
    System.out.println(" tv没有添加到显示界面前,  tv.getRootView().getId() =" + tv.getRootView().getId());
    
    //Log
    tv的根视图 RelativeLayout 的Id = -100
    tv没有添加到显示界面前,  tv.getRootView().getId() =  -100
    

    可以看出两者Id一样,验证了上面的结论.

    参考: android获取根View的方法

    相关文章

      网友评论

          本文标题:四、DecorView 的结构图

          本文链接:https://www.haomeiwen.com/subject/reillftx.html