启动新活动并将其添加到基于片段的布局

时间:2012-07-07 19:51:34

标签: android android-fragments android-activity android-actionbar

我对Fragments API很新,这是我的问题:假设我有ActivityActionBar标签。假设我想从我的应用程序启动消息传递应用程序,通常它将以新的Activity开始。是否可以将消息Activity添加为Activity的新标签?我怎样才能达到这个效果?提前谢谢。

1 个答案:

答案 0 :(得分:1)

在onCreate方法中执行以下操作

      Context context = getApplicationContext();
     ActionBar actionbar = getActionBar();
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab PlayerTab = actionbar.newTab().setText("Fragment A");
    ActionBar.Tab StationsTab = actionbar.newTab().setText("Fragment B");

    Fragment PlayerFragment = new AFragment();
    Fragment StationsFragment = new BFragment();

    PlayerTab.setTabListener(new MsgTabsListener(PlayerFragment, context));
    StationsTab.setTabListener(new MsgTabsListener(StationsFragment, context));

    actionbar.addTab(PlayerTab);
    actionbar.addTab(StationsTab);

然后添加课程MsgTabListener并执行以下操作

class MsgTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public Context context;

public MsgTabsListener(Fragment fragment, Context context) {
    this.fragment = fragment;
    this.context = context;
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {

//Start a new activity here with respect to your main context.
 context.StartActivity(new Intent(....));     

}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    ft.replace(R.id.fragment_container, fragment);
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    ft.remove(fragment);
}

如果你正在寻找好的Fragements API教程,那么Lars Vogel有很好的解释。

http://www.vogella.com/articles/Android/article.html#fragments_tutorial