package com.example.day2;
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.view.View;
import android.widget.RadioGroup;
import com.example.day2.frag.frag01;
import com.example.day2.frag.frag02;
import com.example.day2.frag.frag03;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private RadioGroup radioGroup;
private ArrayList<Fragment> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
pager = findViewById(R.id.vp);
radioGroup = findViewById(R.id.radio_g);
//添加fragment
list = new ArrayList<>();
list.add(new frag01());
list.add(new frag02());
list.add(new frag03());
//添加适配器
pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list.size();
}
});
//设置轮播滑动的联动
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 group, int checkedId) {
switch (checkedId) {
case R.id.r1:
pager.setCurrentItem(0);
break;
case R.id.r2:
pager.setCurrentItem(1);
break;
case R.id.r3:
pager.setCurrentItem(2);
break;
}
}
});
}
}