android TabLayout的简单使用

布局文件

"http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    .support.design.widget.TabLayout
        android:id="@+id/tab_home_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/titleBlue"
        app:tabIndicatorColor="@color/red"
        app:tabSelectedTextColor="@color/gray"
        app:tabTextColor="@color/white"
        />
    .support.v4.view.ViewPager
        android:id="@+id/vp_home_pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />

主代码:

public class HomeFragment extends Fragment {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private List mFragments;
    private String[] mTitles;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View view=LayoutInflater.from(getContext()).inflate(R.layout.fragment_home,null);
        mTabLayout = (TabLayout) view.findViewById(R.id.tab_home_title);
        mViewPager = (ViewPager) view.findViewById(R.id.vp_home_pager);

        initData();

        return view;
    }

    private void initData() {
        mFragments = new ArrayList<>();
        mFragments.add(new NewFragment());
        mFragments.add(new PicFragment());
        mFragments.add(new FootFragment());
        mFragments.add(new GirlsFragment());
        mFragments.add(new SportsFragment());
        mFragments.add(new PeopleFragment());

        mTitles = new String[]{"新闻","图片","美食","美女","体育","人物"};

        mViewPager.setAdapter(new MyPagerAdapter(getFragmentManager()));
        //将TabLayout和ViewPager关联起来。
        mTabLayout.setupWithViewPager(mViewPager);
        //设置可以滑动
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

    }

    class MyPagerAdapter extends FragmentPagerAdapter{


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

        @Override
        public Fragment getItem(int position) {

            return mFragments.get(position);
        }

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

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

自己写的Demo源码

你可能感兴趣的:(笔记)