Adapter:
package com.example.fashionyuan.Adatader;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by 梁Sir on 2017/9/26.
*/
public class Adatader extends FragmentPagerAdapter{
private ArrayList<Fragment>list;
public Adatader(FragmentManager fm, ArrayList<Fragment> list) {
super(fm);
this.list = list;
}
public Adatader(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
}
mian:
package com.example.fashionyuan.main;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.example.fashionyuan.Adatader.Adatader;
import com.example.fashionyuan.Fragment.FragmentA;
import com.example.fashionyuan.Fragment.FragmentB;
import com.example.fashionyuan.Fragment.FragmentC;
import com.example.fashionyuan.Fragment.FragmentD;
import com.example.fashionyuan.Fragment.FragmentE;
import com.example.fashionyuan.R;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, ViewPager.OnPageChangeListener {
private ArrayList<Fragment> list;
private FragmentManager fm;
private ViewPager vp;
private RadioButton[] radioButtons;
private RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
vp = (ViewPager) findViewById(R.id.vp);
rg = (RadioGroup) findViewById(R.id.rg);
radioButtons =new RadioButton[rg.getChildCount()];
for (int i = 0; i <radioButtons.length; i++) {
radioButtons[i] = (RadioButton) rg.getChildAt(i);
}
FragmentA fragmentA=new FragmentA();
FragmentB fragmentB=new FragmentB();
FragmentC fragmentC=new FragmentC();
FragmentD fragmentD=new FragmentD();
FragmentE fragmentE=new FragmentE();
list = new ArrayList<>();
list.add(fragmentA);
list.add(fragmentB);
list.add(fragmentC);
list.add(fragmentD);
list.add(fragmentE);
fm = getSupportFragmentManager();
Adatader adatader = new Adatader(fm,list);
vp.setAdapter(adatader);
radioButtons[0].setChecked(true);
rg.setOnCheckedChangeListener(this);
vp.setOnPageChangeListener(this);
}
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
for (int j = 0; j <radioButtons.length; j++) {
if (radioButtons[j].getId()==i){
vp.setCurrentItem(j);
}
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
radioButtons[position].setChecked(true);
}
@Override
public void onPageScrollStateChanged(int state) {
}
}