如何从TabAdapter中的一个选项卡替换片段?

时间:2012-06-29 10:07:40

标签: android listview android-viewpager fragment

虽然我意识到嵌套片段不是一个选项,但我仍然有一个问题,我根本无法找到答案。

我正在使用ActionBarSherlock的FragmentsTabPager示例创建一个界面,可以通过滑动而不是单击选项卡来浏览选项卡。我的问题是其中一个标签包含一个列表视图。单击此列表视图时,将启动包含新列表的其他片段(基于单击项目的数据)。我该如何做到这一点?

我认为你可能需要我的BaseActivity(使用ViewPager和TabsAdapter

的一点)
*snippet*

public class BaseActivity extends SherlockFragmentActivity {
TabHost mTabHost;
ViewPager  mViewPager;
TabsAdapter mTabsAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_tabs_pager);
    mTabHost = (TabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup();

    mViewPager = (ViewPager)findViewById(R.id.pager);

    mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

    mTabsAdapter.addTab(mTabHost.newTabSpec("home").setIndicator("Home"),
            FragmentStackSupport.CountingFragment.class, null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("players").setIndicator("PLAYERS"),
            PlayerRankingFragment.class, null);
    mTabsAdapter.addTab(mTabHost.newTabSpec("teams").setIndicator("TEAMS"),
            FederationRanksFragment.class, null);

    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
    }
}

/**
 * This is a helper class that implements the management of tabs and all
 * details of connecting a ViewPager with associated TabHost.  It relies on a
 * trick.  Normally a tab host has a simple API for supplying a View or
 * Intent that each tab will show.  This is not sufficient for switching
 * between pages.  So instead we make the content part of the tab host
 * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
 * view to show as the tab content.  It listens to changes in tabs, and takes
 * care of switch to the correct paged in the ViewPager whenever the selected
 * tab changes.
 */
public static class TabsAdapter extends FragmentPagerAdapter
        implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
    private final Context mContext;
    private final TabHost mTabHost;
    private final ViewPager mViewPager;
    private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

    static final class TabInfo {
        private final String tag;
        private final Class<?> clss;
        private final Bundle args;

        TabInfo(String _tag, Class<?> _class, Bundle _args) {
            tag = _tag;
            clss = _class;
            args = _args;
        }
    }
*Snippet*

BaseActivity - &gt;标签“团队” - &gt;团队ListView(AllianceFragment) - &gt;团队项目点击 - &gt;玩家ListView(PlayersFragment)。

最后,这是相关应用的屏幕截图:

https://dl.dropbox.com/u/11917448/Screenshot_2012-06-28-13-32-21.png

1 个答案:

答案 0 :(得分:0)

BTW,现在有了最新的支持库,刚刚添加了嵌套片段支持。请参阅getChildFragmentManager()方法。但要注意内存泄漏。我还在玩弄它们。我在PagerTabStrip和ViewPager中使用它。效果很好。

相关问题