1. 程式人生 > >TabLayout、ViewPager與Fragment

TabLayout、ViewPager與Fragment

1、前言:TabLayout是一種比較常見的佈局控制元件,在很多地方我們經常能看到一些類似於指示器的東西,在這裡,通過與ViewPager的結合來構建一個Android介面的基本框架,FragmentPagerAdapter 來 適配我們的ViewPager與Fragment。此次實踐進行了對Tablayout與ViewPager巢狀。
2、佈局:
第一層TabLayout的佈局xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.design.widget.TabLayout android:background="@color/color_mine" android:id="@+id/table" android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignParentBottom
="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true">
</android.support.design.widget.TabLayout> <com.indicator.NoScrollViewPager android:background="@color/color_mine" android:id="@+id/viewPager" android:layout_width
="match_parent" android:layout_height="match_parent" android:layout_above="@id/table" />
</RelativeLayout>

這裡為了讓ViewPager不能滑動,所以採用新建一個NoScrollViewPager繼承ViewPager的方法,重寫onTouchEvent、onInterceptTouchEvent方法如下:

/**
 * Created by Administrator on 2017/5/31.
 * 禁止ViewPager的滑動
 *
 * ViewPager非常好用,但有時候需要在ViewPager的裡面再嵌入ViewPager,那麼就有衝突了,簡單粗暴的方法就是直接把一個ViewPager禁止滑動。

 注意:禁止滑動的同時不能禁止 setCurrentItem 方法。

 實現思路:重寫ViewPager,覆蓋 onTouchEvent 和 onInterceptTouchEvent 方法,使其返回false,這樣就等於禁止了ViewPager上的滑動事件。
 */

public class NoScrollViewPager extends ViewPager {
    public NoScrollViewPager(Context context) {
        super(context);
    }

    public NoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent arg0) {
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent arg0) {
        return false;
    }
}

第一層TabLayout與NoScrollViewPager 的使用:

public class StartActivity extends AppCompatActivity {


    private String[] mTitles = {"Home","Mine"};
    private ArrayList<Fragment> mFragments = new ArrayList<>();

    private NoScrollViewPager mViewPager;
    private TabLayout tabLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        initViews();
        addFragments();
        setmViewPager();
    }

    private void setmViewPager(){

        TabAdapter tabAdapter = new TabAdapter(getSupportFragmentManager(),mFragments,mTitles);
        mViewPager.setAdapter(tabAdapter);
        tabLayout.setTabTextColors(getResources().getColor(R.color.colorAccent), getResources().getColor(R.color.colorPrimary));//設定文字在選中和為選中時候的顏色
        tabLayout.setupWithViewPager(mViewPager);
    }

    private void addFragments(){
        mFragments.add(new MainFragment());
        mFragments.add(MineFragment.newInstance(1));
    }

    private void initViews(){
        mViewPager = (NoScrollViewPager) findViewById(R.id.viewPager);
        tabLayout = (TabLayout)findViewById(R.id.table);
    }


}

TabAdapter對Fragement進行適配和載入:

public class TabAdapter extends FragmentPagerAdapter {

    private List<Fragment> mFragments;
    private String[] mTitles;

    public TabAdapter(FragmentManager fm, ArrayList<Fragment> fragments,String[] titles){
        super(fm);
        mFragments = fragments;
        mTitles = titles;
    }
    @Override
    public int getCount() {
        return mFragments.size();
    }

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

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

第二層TabLayout與ViewPager的佈局xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.indicator.MainFragment">

    <android.support.design.widget.TabLayout
        android:background="@color/colorPrimary"
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="30dp">

    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager

        android:layout_below="@id/tab_layout"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</RelativeLayout>

在MainFragment嵌套了第二層TabLayout

public class MainFragment extends Fragment {


    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;


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

        mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

        View v = inflater.inflate(R.layout.main_frag,null);

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

        TabLayout   tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
//        ShapeIndicatorView shapeIndicatorView = (ShapeIndicatorView) v.findViewById(R.id.custom_indicator);

        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setupWithViewPager(mViewPager);

//        shapeIndicatorView.setupWithTabLayout(tabLayout);
//        shapeIndicatorView.setupWithViewPager(mViewPager);

        return v;

    }


    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 7;
        }

        @Override
        public CharSequence getPageTitle(int position) {

            return "SECTION "  + position;
        }
    }
}

最後我們實現的效果就是:
這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述