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;
}
}
});
}
}