RadioGroup与ViewPage联动

在开发中我们常用到RadioGroup与viewpage之间的联动
如以下页面常见的方式

代码如下:
MainActivity类

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, ViewPager.OnPageChangeListener {

    private ViewPager mViewPager;
    private RadioGroup mRadioGroup;
    private MainTabAdapter adapter;

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

private void init() {
    mViewPager = (ViewPager) findViewById(R.id.ump_viewpager);
    mRadioGroup = (RadioGroup) findViewById(R.id.rg_ump_layout);
    mRadioGroup.setOnCheckedChangeListener(this);
    mViewPager.setOnPageChangeListener(this);
    adapter = new MainTabAdapter(getSupportFragmentManager(), null);
    mViewPager.setAdapter(adapter);
    mRadioGroup.check(mRadioGroup.getChildAt(0).getId());
    mViewPager.setOffscreenPageLimit(3);
}

@Override
public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
    int index = radioGroup.indexOfChild(radioGroup.findViewById(i));
    mViewPager.setCurrentItem(index);
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

/**
 *选择当前position
 *
 */
@Override
public void onPageSelected(int position) {
    View childView = mRadioGroup.getChildAt(position);
    if (childView instanceof RadioButton) {
        RadioButton radioButton = (RadioButton) childView;
        mRadioGroup.check(radioButton.getId());
    }
}

@Override
public void onPageScrollStateChanged(int state) {

    }
}

MainTabAdapter类

class MainTabAdapter extends FragmentPagerAdapter {
    private String[] mTitles = new String[]{"", "", ""};
    private int[] datas = null;

    public MainTabAdapter(FragmentManager fm, int[]     datas) {
        super(fm);

        this.datas = datas;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        switch (position) {
            case 0://头条
                fragment = Fragment1.getInstance();
                break;
            case 1://评论
                fragment = Fragment2.getInstance();
                break;
            case 2://论坛
                fragment = Fragment3.getInstance();
                break;

        }

        return fragment;
    }

    @Override
    public int getCount() {
        return mTitles.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
    return mTitles[position];
    }
}

xml文件如下:activity_main.xml






    
        

        
        
    




在res目录的drawable下创建background和字体textColor

效果如下:

RadioGroup与ViewPage联动_第1张图片
1497775407(1).png
RadioGroup与ViewPage联动_第2张图片
pinglun.png

下载demo地址RadioGroup与ViewPage联动

你可能感兴趣的:(RadioGroup与ViewPage联动)