我的应用程序中有一个导航栏,我想让导航栏在所有活动中都可用。我想我必须设置contentView两次,但当然这不起作用。
我一直在看,但我没有得到它的工作。我有一个超类,我可以从我的超级类中设置第二个布局吗?
答案 0 :(得分:4)
您应该通过其他布局中的<include>
标记添加导航栏。设置两次内容布局是行不通的,因为Android在回调中基本上总是使用用户最后说的内容。所以
setContentLayout(R.layout.nav);
setContentLayout(R.layout.main);
将导致仅使用主要布局。
查看this article,其中给出了使用include标记的示例。
答案 1 :(得分: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即可。并且您的导航栏将放置在您需要的位置,而不是一遍又一遍地在每个布局中重复,并污染布局(更不用说重复代码来控制每个活动类中的导航)。
答案 2 :(得分:0)