好吧,我决定在我的小程序中使用tabhost会更好。
然而,在android 6.0+下,tabactivity和其他一些已经被弃用。
所以我写了这个:

public class TabMain extends Activity{
@Override
protected void onCreate(Bundle bundle){
    super.onCreate(bundle);

    setContentView(R.layout.tab_main);
    TabHost tabHost = (TabHost)findViewById(R.id.tab_main_tabhost);
    tabHost.setup();//several lines here....}}

当我运行此代码时,IDE会向我抛出一个RunTimtException:
“java.lang.IllegalStateException:是否忘记调用“public void setup(localActivityManager ActivityGroup)”?
我发现activitygroup也被弃用了。
我该怎么绕过这个?

最佳答案

试试这个

<android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"/>
        <android.support.v4.view.ViewPager
            android:id="@+id/home_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

在你的活动中
viewPager = (ViewPager) findViewById(R.id.home_viewpager);
        viewPager.setOffscreenPageLimit(4);
        if (viewPager != null) {
            setupViewPager(viewPager);
        }
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

方法是
private void setupViewPager(ViewPager viewPager) {
        adapter = new Adapter(getSupportFragmentManager());
        adapter.addFragment(new Store(), "Store");//fragment class name
        adapter.addFragment(new Post(), "GG Connect");//fragment class name


        viewPager.setAdapter(adapter);

    }
    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

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

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }

07-27 17:17