2017-01-16 48 views
0

我想獲得此示例android xml佈局的頂級佈局。我所指的頂級是將整個活動放在一起的ViewGroup。Android:如何獲取活動的頂級父級佈局

我知道

getWindow().getDecorView().findViewById(android.R.id.content); 

但我不需要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> 

我需要得到的RelativeLayout(這是頂級佈局我指的是,請糾正我,如果我錯了,我的術語)。我可以通過使用下面的代碼來獲得它。

WebView webView = (WebView) findViewById(R.id.my_webview); 
webview.getParent().getParent() 

但是,如果佈局嵌套更深什麼樣

<Layout> 
    <Layout> 
     <Layout> 
      <Webview/> 
     <Layout> 
    <Layout> 
<Layout> 

如何能夠得到頂級佈局不使用的getParent()。謝謝!

+1

在您的.XML中爲您的parent_layout指定id,並在您的MainActivity中定義/轉換此ID並根據需要使用此ID。 –

+0

我在一個我可以用於不同應用程序的庫中調用它。現在,這個id不適用於這個。 p.s:在使用庫的每個應用程序中,id可能不同。所以我唯一可以參考的是webview對象。 – Aaron

+0

我創建了此代碼,但尚未測試https://hastebin.com/ijiyusicul.cs。 – Enzokie

回答

1

在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> 

在你的活動

RelativeLayout parentLayout=(RelativeLayout)findViewById(R.id.parentLayout); 

getWindow().getDecorView().getRootView(); 

getWindow().getDecorView().findViewById(android.R.id.content); 

ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this 
      .findViewById(android.R.id.content)).getChildAt(0); 
+0

我在一個我可以用於不同應用程序的庫中調用它。現在,這個id不適用於這個。 p.s:在使用庫的每個應用程序中,id可能不同。所以我唯一可以參考的是webview對象。 – Aaron

+0

如果您不需要getDecorView(),您可以嘗試查看組 –