简单实现ViewPager+TabLayout+Fragment滑动切换

实现效果

简单实现ViewPager+TabLayout+Fragment滑动切换_第1张图片

 

在build.gradle中添加

  implementation 'com.android.support:design:27.1.0'

 

activity_main.xml文件



    

    
    

 

MainActivity文件

public class MainActivity extends AppCompatActivity {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private List mTitle;
    private List mFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
        initData();
        initView();
    }

    private void initData(){
        mTitle=new ArrayList<>();
        mTitle.add("Tab0");
        mTitle.add("Tab1");

        mFragment=new ArrayList<>();
        mFragment.add(new FitstFragment());
        mFragment.add(new SecondFragment());
    }

    private void initView(){
        mTabLayout=findViewById(R.id.mTabLayout);
        mViewPager=findViewById(R.id.mViewPager);
        //预加载
        mViewPager.setOffscreenPageLimit(mFragment.size());
        //mViewPager滑动监听
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        //设置适配器
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            //选中的item
            @Override
            public Fragment getItem(int i) {
                return mFragment.get(i);
            }
            //返回item的个数
            @Override
            public int getCount() {
                return mFragment.size();
            }
            //设置标题
            @Override
            public CharSequence getPageTitle(int position) {
                return mTitle.get(position);
            }
        });
        //绑定
        mTabLayout.setupWithViewPager(mViewPager);
    }
}

 

其中一个的Fragment 

FirstFragment.java

public class FitstFragment extends Fragment  {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        findView(view);
        return view;
    }

    private void findView(View view) {

    }

}

Fragment的布局文件fragment_first.xml




    

 

你可能感兴趣的:(android)