[英]2 layouts 1 activity android
我的應用程序中有一個導航欄,問題是我希望導航欄可用於所有活動。 我想我必須設置contentView兩次,但當然這不起作用。
我一直在看,但我不能讓它工作。 我有一個超級課程,我可以從我的超級課程中設置第二個布局嗎?
您應該通過其他布局中的<include>
標記包含導航欄。 設置兩次內容布局是行不通的,因為Android在回調中基本上總是使用用戶最后說的內容。 所以
setContentLayout(R.layout.nav);
setContentLayout(R.layout.main);
將導致僅使用主要布局。
看一下這篇文章 ,它給出了使用include標簽的一個例子。
您可以擴展標准活動(Activity,ListActivity等等,如果您使用其他任何活動)並將其用作包含nav_bar的基礎。
例如:
像這樣用nabar定義布局
<LinearLayout
...
android:orientation="vertical"
>
<YourNavBarComponent
...
/>
<FrameLayout
android:id="@+id/nav_content"
...
>
// Leave this empty for activity content
</FrameLayout>
</LinearLayout>
這將是您的基本布局,以包含nav_content框架中的所有其他布局。 接下來,在創建基本活動類時,執行以下操作:
public abstract class NavActivity extends Activity {
protected LinearLayout fullLayout;
protected FrameLayout navContent;
@Override
public void setContentView(final int layoutResID) {
fullLayout= (LinearLayout) getLayoutInflater().inflate(R.layout.nav_layout, null); // Your base layout here
navContent= (FrameLayout) fullLayout.findViewById(R.id.nav_content);
getLayoutInflater().inflate(layoutResID, navContent, true); // Setting the content of layout your provided in the nav_content frame
setContentView(fullLayout);
// here you can get your navigation buttons and define how they should behave and what must they do, so you won't be needing to repeat it in every activity class
}
}
現在,當您創建一個需要導航欄的新活動時,只需擴展NavActivity即可。 並且您的導航欄將被放置在您需要的位置,而不是一遍又一遍地在每個布局中重復,並污染布局(更不用說重復代碼來控制每個活動類中的導航)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.