欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

安卓的fragment切换+左右滑动

程序员文章站 2022-05-05 14:21:18
...

viewpage控件:

public class ShowActivity extends AppCompatActivity {

private ViewPager pager;
private RadioGroup radioGroup;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show);
    ButterKnife.bind(this);

获取资源ID

    pager = findViewById(R.id.viewpager);
    radioGroup = findViewById(R.id.radioGroup);

选中第一个

    radioGroup.check(radioGroup.getChildAt(0).getId());

添加fragment页

    final ArrayList<Fragment> list = new ArrayList<>();
    list.add(new FragOne());
    list.add(new FragTwo());
    list.add(new FragThree());
    list.add(new FragFour());
    list.add(new FragFive());

内部类adapter

    pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int i) {
            return list.get(i);
        }

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

viewpage切换

    pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {
            radioGroup.check(radioGroup.getChildAt(i).getId());
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });

滑动选中相应的下标

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch (i){
                case R.id.radio0:
                    pager.setCurrentItem(0);
                    break;
                case R.id.radio1:
                    pager.setCurrentItem(1);
                    break;
                case R.id.radio2:
                    pager.setCurrentItem(2);
                    break;
                case R.id.radio3:
                    pager.setCurrentItem(3);
                    break;
                case R.id.radio4:
                    pager.setCurrentItem(4);
                    break;
            }
        }
    });
}