使用ViewPageIndicator在SherlockFragment中使用Tabhost

时间:2012-11-14 15:42:41

标签: java android android-fragments android-tabhost actionbarsherlock

所以我有3个Sherlock Fragments设置并且与ViewPageIndicator一起正常工作。我现在要做的是在其中一个片段中放置一个TabHost,以便它显示2个单独的标签(在底部)。我相信这意味着我需要再将2个碎片放入由TabHost控制的第3个碎片中。

考虑到需要在Fragment中创建TabHost,我不确定如何正确创建它。

以下是我从this tutorial开始工作的片段的代码,我试图更新以添加TabHost失败:

TestFragment3.java

public class TestFragment3 extends SherlockFragment {
private String mContent = "none";

public static TestFragment3 newInstance(String text) {
    TestFragment3 fragment = new TestFragment3();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    args.putString(KEY_TAB_NUM, text);
    fragment.setArguments(args);

    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_main, null);
    String text = getString(R.string.tab_page_num) + mContent;
    ((TextView)view.findViewById(R.id.text)).setText(text);

    return view;
}

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   mContent =  getArguments() != null ? getArguments().getString(KEY_TAB_NUM) : "none";
}

}

MainActivity.java

public class MainActivity extends SherlockFragmentActivity {

private static final String[] TAB_TITLES = new String[] { "This", "Is", "A", "ViewPager" };

TestFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;

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

    setContentView(R.layout.simple_tabs);

    mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);

    mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
}

class TestFragmentAdapter extends FragmentPagerAdapter {     
    private int mCount = TAB_TITLES.length;

    public TestFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return TestFragment.newInstance(String.valueOf(position));
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return TAB_TITLES[position];
    }
}
}

我是否需要创建一个新的SherlockFragmentActivity并将另外两个SherlockFragments添加到该TabHost?如果是这样,我如何设置MainActivity with 3 Fragments以使用另一个Activity而不是Fragment作为其第三个片段?

我试图将片段放入片段中时出现此错误...

11-14 19:10:54.271: E/AndroidRuntime(2812): java.lang.IllegalStateException: Recursive entry to executePendingTransactions
11-14 19:10:54.271: E/AndroidRuntime(2812):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1388)
11-14 19:10:54.271: E/AndroidRuntime(2812):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431)
11-14 19:10:54.271: E/AndroidRuntime(2812):     at com.example.demolistview.EventInviteesFragment$TabManager.onTabChanged(EventInviteesFragment.java:152)
11-14 19:10:54.271: E/AndroidRuntime(2812):     at android.widget.TabHost.invokeOnTabChangeListener(TabHost.java:391)
11-14 19:10:54.271: E/AndroidRuntime(2812):     at android.widget.TabHost.setCurrentTab(TabHost.java:376)
11-14 19:10:54.271: E/AndroidRuntime(2812):     at android.widget.TabHost.addTab(TabHost.java:236)
...
...
...

2 个答案:

答案 0 :(得分:4)

关于这个问题:

  

考虑到需要在Fragment中创建TabHost,我不是   确定如何正确创建它。

如果您查看最新的支持演示,他们会举例说明您要实施的内容。可以通过SDK Manager下载它们。

这就是他们如何在片段中嵌套标签主机。该设置使用Child FragmentManager。

public class FragmentTabsFragmentSupport extends Fragment {
    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragment1);

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
                FragmentStackSupport.CountingFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
                LoaderCursorSupport.CursorLoaderListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
                LoaderCustomSupport.AppListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
                LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);

        return mTabHost;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTabHost = null;
    }
}

我还创建了一个小例子,可以在https://github.com/marsucsb/nested-fragments

找到

答案 1 :(得分:1)

没有测试过,但应该是这样的

TabFragment extends SherlockFragment {
TabHost mTabHost;
    TabManager mTabManager;

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

                 mTabManager = new TabManager(this.getActivity(), mTabHost, R.id.realtabcontent);

                 mTabManager.addTab(mTabHost.newTabSpec("first").setIndicator("First", getResources().getDrawable(R.drawable.ic_tab_first_tab)), FirstFragment.class  , null);

                 mTabManager.addTab(mTabHost.newTabSpec("second").setIndicator("Second", getResources().getDrawable(R.drawable.ic_tab_second_tab)), SecondFragment.class  , null);
 public static class TabManager implements TabHost.OnTabChangeListener {
            private final FragmentActivity mActivity;
            private final TabHost mTabHost;
            private final int mContainerId;
            private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
            TabInfo mLastTab;

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

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

            static class DummyTabFactory implements TabHost.TabContentFactory {
                private final Context mContext;

                public DummyTabFactory(Context context) {
                    mContext = context;
                }


                public View createTabContent(String tag) {
                    View v = new View(mContext);
                    v.setMinimumWidth(0);
                    v.setMinimumHeight(0);
                    return v;
                }
            }

            public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
                mActivity = activity;
                mTabHost = tabHost;
                mContainerId = containerId;
                mTabHost.setOnTabChangedListener(this);
            }

            public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
                tabSpec.setContent(new DummyTabFactory(mActivity));
                String tag = tabSpec.getTag();

                TabInfo info = new TabInfo(tag, clss, args);

                // Check to see if we already have a fragment for this tab, probably
                // from a previously saved state.  If so, deactivate it, because our
                // initial state is that a tab isn't shown.
                info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
                if (info.fragment != null && !info.fragment.isDetached()) {
                    FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                    ft.detach(info.fragment);
                    ft.commitAllowingStateLoss();
                }

                mTabs.put(tag, info);
                mTabHost.addTab(tabSpec);
            }


            public void onTabChanged(String tabId) {
                TabInfo newTab = mTabs.get(tabId);
                if (mLastTab != newTab) {
                    FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                    if (mLastTab != null) {
                        if (mLastTab.fragment != null) {
                            ft.detach(mLastTab.fragment);
                        }
                    }
                    if (newTab != null) {
                        if (newTab.fragment == null) {
                            newTab.fragment = Fragment.instantiate(mActivity,
                                    newTab.clss.getName(), newTab.args);
                            ft.add(mContainerId, newTab.fragment, newTab.tag);
                        } else {
                            ft.attach(newTab.fragment);
                        }
                    }

                    mLastTab = newTab;
                    ft.commitAllowingStateLoss();
                    mActivity.getSupportFragmentManager().executePendingTransactions();
                }
            }
        }
}

您的图片布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

     <LinearLayout 
        android:orientation="vertical" 
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">



        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:layout_height="wrap_content">

        <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

        </FrameLayout>

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_marginBottom="-4dp"
            android:background="#333333" 
            android:layout_height="wrap_content" 
         />


        </LinearLayout>
</TabHost>

</LinearLayout>