我想同时为每个相应的操作栏选项卡添加片段

时间:2015-01-29 23:26:05

标签: android android-fragments android-actionbar android-viewpager

更新:我不明白为什么当点击TabSelected()上的每个标签时,即使它已经被添加到fragmentTransaction android.R.id.content中,也没有显示正确的片段。
    我在调用onTabSelected之前调用此方法以确保片段不为空。

   protected void initTabs() {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                if(mShowFragment3 == null) {


                    mShowFragment3 = EpisodeTileFragment.newInstance(getString(R.string.title_section4));
                    ft.add(android.R.id.content, mShowFragment3);
                } 
                if(mShowFragment2 == null) {
                    mShowFragment2 = EpisodeTileFragment.newInstance(getString(R.string.title_section3));
                    ft.add(android.R.id.content, mShowFragment2);
                } 
}
    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction ft) {
    //this usually works, but if i try to mess with adding the tabs to the 
    //FragmentTransaction this won't work anymore
    if(tab.getPosition() == 1) {
       ft.show(mShowFragment2);
    }

我已经在互联网上搜索过,这可能是不可能的,但我想给它一个机会。

我目前的应用程序运行正常,它有4个标签和4个相应的片段。当用户打开应用程序时,onTabSelected被调用并选择添加第一个标签/片段,我们一切都很好。

用户单击tab2并添加并呈现第二个片段。当用户单击第二个选项卡时,会有一个asynctask获取数据并将其呈现在片段上。等等......这也发生在标签3和4上。当用户第一次实例化片段并将其添加到fragmentTransaction时单击选项卡时,下次单击选项卡时它会快速闪烁,因为它已经添加了,我就是这样隐藏和显示片段。

我的问题是,有没有办法同时加载所有4个标签,而不是等待用户点击标签然后让onTabSelected触发和抓取数据等。如果有,请告诉我有任何问题,代码没有错误,只是不是我想要的,我不知道如何同时实例化所有4个片段。

mSectionsPagerAdapter = new SectionsPagerAdapter(this.getSupportFragmentManager());


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

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {   
            LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
            View tabView = inflater.inflate(R.layout.tab_title, null);

            TextView titleTV = (TextView) tabView.findViewById(R.id.action_custom_title);
            titleTV.setText(mSectionsPagerAdapter.getPageTitle(i));
            titleTV.setTypeface(Typeface.createFromAsset(getAssets(), getString(R.string.tab_font)));
            titleTV.setSingleLine();
            titleTV.setTextSize(13);
            Tab t = actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))                 
                    .setTabListener(this);

            t.setCustomView(tabView);

            actionBar.addTab(t);
        }

这是为了添加标签。但需要为每个标签添加片段。

1 个答案:

答案 0 :(得分:0)

将屏幕外页面限制设置为选项卡数量,然后ViewPager将在创建父活动时呈现所有片段。

mViewPager.setOffscreenPageLimit(4);

你还应该查看Class Overview of ViewPager,它有一个很好的例子,使用一个名为TabsAdapter的自定义FragmentPagerAdapter和一个ViewPager(而不是使用ADT生成的SectionsPagerAdapter)。我在下面的官方Android文档中添加了代码:

public class ActionBarTabsPager extends Activity {
    ViewPager mViewPager;
    TabsAdapter mTabsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.pager);
        setContentView(mViewPager);

        final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

        mTabsAdapter = new TabsAdapter(this, mViewPager);
        mTabsAdapter.addTab(bar.newTab().setText("Simple"),
                CountingFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("List"),
                FragmentPagerSupport.ArrayListFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("Cursor"),
                CursorFragment.class, null);

        if (savedInstanceState != null) {
            bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

    /**
     * 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 ActionBar.TabListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

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

            TabInfo(Class<?> _class, Bundle _args) {
                clss = _class;
                args = _args;
            }
        }

        public TabsAdapter(Activity activity, ViewPager pager) {
            super(activity.getFragmentManager());
            mContext = activity;
            mActionBar = activity.getActionBar();
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
            TabInfo info = new TabInfo(clss, args);
            tab.setTag(info);
            tab.setTabListener(this);
            mTabs.add(info);
            mActionBar.addTab(tab);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                }
            }
        }

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

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