2012-03-05 70 views
0

我正在開發一個Android 2.1應用程序。新手:設置內容視圖由兩部分組成

我已經定義了一個LinearLayout

public class MyTopBar extends LinearLayout { 
    ... 
} 

然後,我有一個佈局xml文件(content.xml):

<LinearLayout> 
    ... 
</LienarLayout> 

我有RootActivity.java,我想設置MyTopBar作爲此RootActivity中的內容。

然後,我有MyActivity延伸RootActivity

public class MyActivity extends RootActivity{ 
     //set xml layout as content here  
} 

我想設置的content.xml爲MyActivity的內容。

總的來說,我想用上面的方式來實現MyTopBar應該位於之上的佈局,總是在屏幕上的。其他延伸RootActivity的活動的內容低於MyTopBar。如何實現這一點??

回答

1

1你可以直接添加自定義LinearLayoutMyActivity類的XML佈局是這樣的:

<LinearLayout> 
    <com.full.package.MyTopBar 
     attributes here like on any other xml views 
    /> 
    ... 
</LinearLayout> 

,或者您可以使用include標籤包括與自定義視圖的佈局:

<LinearLayout> 
    <include layout="@layout/xml_file_containing_mytopbar" 
    /> 
    ... 
</LinearLayout> 

2用途:

setContentView(R.layout.other_content); 
+0

嗨,我已更新我的文章,請看看。基本上,我想將MyTopBar從XML佈局中分離出來,以便我只在RootActivity中啓動MyTopBar,其他擴展根活性的活動只設置xml內容,作爲一個整體,我希望在屏幕上方顯示MyTopBar,並使用其他xml下面的佈局顯示... – 2012-03-05 09:54:37

+0

@ Leem.fin我知道你在做什麼,可能是你所有活動的一個酒吧。我認爲最好的辦法是使用'include'標籤,並簡單地包含一個只包含您自己的自定義視圖的xml佈局。你不能在'RootActivity'中設置'contentView',因爲它將在子類中被替換。 – Luksprog 2012-03-05 10:08:03

+0

@ Leem.fin這裏是一個鏈接從谷歌http://developer.android.com/resources/articles/layout-tricks-reuse.html – Luksprog 2012-03-05 10:10:39

0

爲TopBar騰出佈局,並使用layout.addView(topbarObject); 將Topbar添加到它中關於第二個問題,據我所知,setContentView只能調用一次。然而,您可以使用View.inflate(other_content.xml)來擴充這兩個xml文件,並在您需要時在父xml佈局中添加。您可以在父佈局上使用removeView(),在使用新的佈局文件。

編輯: 對於這兩個問題的解決方案,你可以有一個父佈局的例如。像下面這樣:

//Omitting the obvious tags 
//parent.xml 
<RelativeLayout 
    android:id="@+id/parentLayout"> 
    <RelativeLayout 
     android:id="@+id/topLayout"> 
    </RelativeLayout> 
    <RelativeLayout 
     android:id="@+id/contentLayout"> 
    </RelativeLayout> 
</RelativeLayout> 

現在在代碼中設置父佈局內容視圖,讓你的頂欄佈局的對象,並將其添加到topLayout。

setContentView(R.layout.parent); 
MyTopBar topBar=new MyTopBar(this); 
RelativeLayout toplayout=(RelativeLayout)findViewByid(R.id.topLayout); 
topLayout.addView(topBar); //or you can directly add it to the parentLayout, but it won't work for the first question. So better stick to it. 

現在膨脹所需的xml佈局。並將其添加到contentLayout。

RelativeLayout layout=(RelativeLayout)View.inflate(R.layout.content,null); 
contentLayout.addView(layout);//Assuming you've done the findViewById on this. 

當您需要顯示其他內容xml時,只需調用以下代碼即可。

contentLayout.removeAllView(); 
RelativeLayout layout2=(RelativeLayout)View.inflate(R.layout.other_content,null); 
contentLayout.addView(layout2); 
+0

嗨,聽起來很好的解決方案,你可以請更具體的代碼。謝謝。 (至少第一個,希望也是我的第二個問題的答案) – 2012-03-05 09:58:56

+0

我已經更新了我的答案,有完整的代碼,但由於我的懶惰,我已經省略了一些明顯的東西。我希望你能填補它們。 – noob 2012-03-05 10:13:02