美文网首页
TabLayout、ViewPager与Fragment

TabLayout、ViewPager与Fragment

作者: zhong_bao | 来源:发表于2017-07-04 10:21 被阅读0次

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;
        }
    }
}

最后实现的效果如下图所示:

![ ![tab3.png](https://img.haomeiwen.com/i6179054/79e5c7fc571ffa20.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ](https://img.haomeiwen.com/i6179054/daa60db8e830fc99.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

相关文章

网友评论

      本文标题:TabLayout、ViewPager与Fragment

      本文链接:https://www.haomeiwen.com/subject/xlmthxtx.html