Fragment+ViewPager滑动

package com.bawei.day04;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioGroup;

import com.bawei.day04.fragment.Frag01;
import com.bawei.day04.fragment.Frag02;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private ViewPager viewPager;
private RadioGroup radioGroup;
private ArrayList<Fragment> list;

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

    viewPager = findViewById(R.id.vp);
    radioGroup = findViewById(R.id.radioG);
    //页面数据
    list = new ArrayList<>();
    list.add(new Frag01());
    list.add(new Frag02());
    //viewPager 适配器
    viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

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

    //滑动的时候切换按钮选中状态
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            radioGroup.check(radioGroup.getChildAt(position).getId());
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    //点击按钮切换
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch(i){
                case R.id.r1:
                    viewPager.setCurrentItem(0,false);
                    break;
                case R.id.r2:
                    viewPager.setCurrentItem(1,false);
                    break;
            }
        }
    });
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值