android官方实现Tab(二)

创建Swipe Views 和 Tabs

Swipe views 提供了在姐妹页面之间的横向导航功能,本课程将教给你怎么去创建一个带有swipe view的tab layout,以方便的在tab之间进行选择,另外还向大家介绍怎么创建一个title strip去代替tabs。

实现Swipe Views

你可以使用supportlibrary中的ViewPager来在app中创建swipeview,在viewpager布局中每个子view是一个单独的页面(也就是子view之间通过滑动来展示)。

设置viewpager的布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager  xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" />

要插入子view,需要用到adapter,有两种adapter可以供你选择:

FragmentPagerAdapter
这种方式适合页面相对较小的情况。

FragmentStatePagerAdapter
这种方式适合用集合来定义页面,并且页面的个数是未定的,这种方式有一个特性:当我们从Afragment滑动到Bfragment时候,Afragment会被销毁,使内存的使用达到极小化。

例如,下面使用FragmentStatePagerAdapter的例子:

public class CollectionDemoActivity extends FragmentActivity {
    // When requested, this adapter returns a DemoObjectFragment,
    // representing an object in the collection.
    DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
    ViewPager mViewPager;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collection_demo);

        // ViewPager and its adapters use support library
        // fragments, so use getSupportFragmentManager.
        mDemoCollectionPagerAdapter =
                new DemoCollectionPagerAdapter(
                        getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mDemoCollectionPagerAdapter);
    }
}

// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
    public DemoCollectionPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DemoObjectFragment();
        Bundle args = new Bundle();
        // Our object is just an integer :-P
        args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return "OBJECT " + (position + 1);
    }
}

// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
    public static final String ARG_OBJECT = "object";

    @Override
    public View onCreateView(LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        // The last two arguments ensure LayoutParams are inflated
        // properly.
        View rootView = inflater.inflate(
                R.layout.fragment_collection_object, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                Integer.toString(args.getInt(ARG_OBJECT)));
        return rootView;
    }
}

以上代码只是展示了fragment的滑动,下面展示的是怎么添加tab

添加tab到Action Bar上

要使用actionbar创建tabs,你需要使用NAVIGATION_MODE_TABS,然后创建several个ActionBar.Tab实例,并且为每一个实例实现一个
ActionBar.TabListener接口,如下代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    final ActionBar actionBar = getActionBar();
    ...

    // Specify that tabs should be displayed in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create a tab listener that is called when the user changes tabs.
    ActionBar.TabListener tabListener = new ActionBar.TabListener() {
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            // show the given tab
        }

        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
            // hide the given tab
        }

        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
            // probably ignore this event
        }
    };

    // Add 3 tabs, specifying the tab's text and TabListener
    for (int i = 0; i < 3; i++) {
        actionBar.addTab(
                actionBar.newTab()
                        .setText("Tab " + (i + 1))
                        .setTabListener(tabListener));
    }
}

用swipe views来改变tabs

当用户滑动页面的时候,想要tab跟着做出相应的改变,我们应该在ActionBar.TabListener的回调方法中调用viewpager的setCurrentItem()方法:

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    // Create a tab listener that is called when the user changes tabs.
    ActionBar.TabListener tabListener = new ActionBar.TabListener() {
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            // When the tab is selected, switch to the
            // corresponding page in the ViewPager.
            mViewPager.setCurrentItem(tab.getPosition());
        }
        ...
    };
}

同样,你也可以通过实现ViewPager.OnPageChangeListener接口来改变当前的tab:

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setOnPageChangeListener(
            new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // When swiping between pages, select the
                    // corresponding tab.
                    getActionBar().setSelectedNavigationItem(position);
                }
            });
    ...
}

效果:

android官方实现Tab(二)_第1张图片

使用Title Strip代替Tabs

如果你不想要包含一个action bar,并且更喜欢一个能够滚动的tabs,你可以使用PagerTitleStrip来实现swipe view。

<android.support.v4.view.ViewPager  xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent">

    <android.support.v4.view.PagerTitleStrip  android:id="@+id/pager_title_strip" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:background="#33b5e5" android:textColor="#fff" android:paddingTop="4dp" android:paddingBottom="4dp" />

</android.support.v4.view.ViewPager>

效果:

android官方实现Tab(二)_第2张图片

文章原文与样例代码下载

文章翻译自android官方文档,如果有用,留个足迹可好!

你可能感兴趣的:(tab,Android官方,fragementa,swipe-view,title-stri)