ViewPager+TabLayout+Fragment最简单的实现

首先是布局文件
activity_main.xml




    

        
            

        

        

        

    

fragment.xml




    


步骤1
重写FragmentAdapter

public class MyFragmentAdapter extends FragmentPagerAdapter {

    List list;
    List title;

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

    public MyFragmentAdapter(FragmentManager fm, List list, List title) {
        super(fm);
        this.list = list;
        this.title = title;
    }

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

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

/*让TabLayout能获取到title*/
    @Override
    public CharSequence getPageTitle(int position) {
        return title.get(position);
    }
}

步骤2
viewpager设置adapter

        MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(), fragments, titleList);
        binding.vpGank.setAdapter(adapter);

步骤3
设置TabLayout

        binding.tabGank.setTabMode(TabLayout.MODE_FIXED);
        binding.tabGank.setupWithViewPager(binding.vpGank);//与viewpager联系起来

完整的MainActivity

public class MainActivity extends AppCompatActivity {


    public ActivityMainBinding binding;
    public List fragments;
    public List titleList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main);
        initFragmentList();
        initViewPager();
    }

    public void initFragmentList() {
        fragments = new ArrayList<>();
        titleList = new ArrayList<>();
        fragments.add(new MyFragment1());
        fragments.add(new MyFragment1());
        fragments.add(new MyFragment1());
        titleList.add("1");
        titleList.add("2");
        titleList.add("3");
    }

    public void initViewPager() {
        MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(), fragments, titleList);
        binding.vpGank.setAdapter(adapter);
        //adapter.notifyDataSetChanged();
        binding.tabGank.setTabMode(TabLayout.MODE_FIXED);
        binding.tabGank.setupWithViewPager(binding.vpGank);
    }
}

完成啦!

你可能感兴趣的:(ViewPager+TabLayout+Fragment最简单的实现)