Android:如何获取活动的顶级父布局

Aar*_*ron 2 android android-layout

我想获得这个示例 android xml 布局的顶级布局。我指的顶层是将整个活动结合在一起的 ViewGroup。

我知道

getWindow().getDecorView().findViewById(android.R.id.content);
Run Code Online (Sandbox Code Playgroud)

但我不需要 DecorView。

请参考下面的xml。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout">
        <WebView
        android:id="@+id/my_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    </LinearLayout>


</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我需要获取RelativeLayout(这是我指的顶级布局,如果我的术语有误,请纠正我)。我可以使用下面的代码来获取它。

WebView webView = (WebView) findViewById(R.id.my_webview);
webview.getParent().getParent()
Run Code Online (Sandbox Code Playgroud)

但是,如果布局嵌套得更深怎么办?

<Layout>
    <Layout>
       <Layout>
          <Webview/>
       <Layout>
    <Layout>
<Layout>
Run Code Online (Sandbox Code Playgroud)

如何在不使用 getParent() 的情况下获得顶级布局。谢谢!

san*_*mar 5

在 XML 中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
 android:id="@+id/parentLayout">

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout">
        <WebView
        android:id="@+id/my_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    </LinearLayout>


</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

在你的活动中

 RelativeLayout parentLayout=(RelativeLayout)findViewById(R.id.parentLayout);
Run Code Online (Sandbox Code Playgroud)

或者

getWindow().getDecorView().getRootView();
Run Code Online (Sandbox Code Playgroud)

或者

getWindow().getDecorView().findViewById(android.R.id.content);
Run Code Online (Sandbox Code Playgroud)

或者

ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
            .findViewById(android.R.id.content)).getChildAt(0);
Run Code Online (Sandbox Code Playgroud)