TabLayout和ViewPager切换

TabLayout和ViewPager切换_第1张图片 标题

 

 

 

实现一个类似这样的(纯文字效果),以下是源代码------>

 

***.xml




    

    

 

 

***Activity.java

 

public class MainActivity extends FragmentActivity {

    private TabLayout tablayout;
    private ViewPager viewpager;
    private ArrayList fragments;
    private ArrayList titles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        tablayout = findViewById(R.id.tablayout);
        viewpager = findViewById(R.id.viewpager);
        //vp的数据源
        fragments = new ArrayList<>();
        fragments.add(new FirstFragment());
        fragments.add(new SecondFragment());
        fragments.add(new ThirdFragment());

        viewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });
        tablayout.setupWithViewPager(viewpager);
        //tablayout的数据源
        titles = new ArrayList<>();
        titles.add("First");
        titles.add("Second");
        titles.add("Third");
        for (int i = 0; i < titles.size(); i++) {
            tablayout.getTabAt(i).setText(titles.get(i));
        }

    }
}

 

 

 

 

 

你可能感兴趣的:(fragment)