开发者

2 layouts 1 activity android

开发者 https://www.devze.com 2023-02-08 06:51 出处:网络
I have a navigation bar in my app, the thing is that I want the navbar to be available in all activities. I s开发者_如何转开发uppose that I have to set contentView two times, but that doesn\'t work, o

I have a navigation bar in my app, the thing is that I want the navbar to be available in all activities. I s开发者_如何转开发uppose that I have to set contentView two times, but that doesn't work, of course.

I've been looking at and but I dont get it to work. I have a super class, can I set this second layout from my super class?


You should include the nav bar via <include> tag from the other layouts. Setting the content layout twice will not work, as Android is in the callbacks basically always using what the user has told last. So

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

will result in only the main layout being used.

Have a look at this article which gives an example of using the include tag.


You can extend standard activities (Activity, ListActivity, etc.. if you use any others) and use them as a base for including a nav_bar.

For example:

Define a layout with nabar like this

<LinearLayout
  ...
  android:orientation="vertical"
>
  <YourNavBarComponent
    ...
  />
  <FrameLayout
    android:id="@+id/nav_content"
    ...
  >
    // Leave this empty for activity content
  </FrameLayout>
</LinearLayout>

This will be your base layout to contain all other layouts in the nav_content frame. Next, in create a base activity class, and do the following:

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

And now, when you create a new activity, where you need a nav bar, just extend NavActivity instead. And your nav bar will be placed where you need it, without repeating it in every layout over and over again, and polluting the layouts (not to mention repeating a code to control navigation in every activity class).


Try merging layouts, as described on Android Developers Blog.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号