2011-02-04 108 views
3

我在我的應用程序中有一個導航欄,事情是我想讓導航欄在所有活動中都可用。我想我必須設置contentView兩次,但這當然不起作用。2佈局1活動android

我一直在看,但我沒有得到它的工作。我有一個超類,我可以從我的超類設置第二個佈局嗎?

回答

4

您應該通過其他佈局的<include>標籤包含導航欄。設置內容佈局兩次將不起作用,因爲Android基本上始終使用用戶最後告訴的回調。因此,

setContentLayout(R.layout.nav); 
setContentLayout(R.layout.main); 

將導致只使用主佈局。

看看this article,它給出了使用include標籤的例子。

+0

你的意思是我必須在每個佈局中編寫相同的佈局,還是應該使用標記? – madcoderz 2011-02-04 09:15:12

+1

使用include標籤包含導航欄。將更新我的答案,使其更清楚。 – 2011-02-04 09:16:46

2

您可以擴展標準活動(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代替。並且您的導航欄將被放置在您需要的位置,而不會在每個佈局中一遍又一遍地重複它,並且污染布局(更不用說重複一個代碼來控制每個活動類中的導航)。