Viewpager+Fragment联动

2017-10-23  本文已影响0人  Meimaobing

package com.example.taobao;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.RadioGroup;

import com.example.taobao.Fragment.Fieve;
import com.example.taobao.Fragment.Four;
import com.example.taobao.Fragment.One;
import com.example.taobao.Fragment.Three;
import com.example.taobao.Fragment.Two;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends FragmentActivity {
ViewPager vp;
RadioGroup rg;
List<Fragment> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//找控件
vp= (ViewPager) findViewById(R.id.vp);
rg= (RadioGroup) findViewById(R.id.rg);
initData();
MyAdpter adpter=new MyAdpter(getSupportFragmentManager());
vp.setAdapter(adpter);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (i)
{
case R.id.rb1:
vp.setCurrentItem(0);
break;
case R.id.rb2:
vp.setCurrentItem(1);
break;
case R.id.rb3:
vp.setCurrentItem(2);
break;
case R.id.rb4:
vp.setCurrentItem(3);
break;
case R.id.rb5:
vp.setCurrentItem(4);
break;
}
}
});
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position)
            {
                case 0:
                    rg.check(R.id.rb1);
                    break;
                case 1:
                    rg.check(R.id.rb2);
                    break;
                case 2:
                    rg.check(R.id.rb3);
                    break;
                case 3:
                    rg.check(R.id.rb4);
                    break;
                case 4:
                    rg.check(R.id.rb5);
                    break;
            }

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

}

private void initData() {
    list=new ArrayList<Fragment>();
    list.add(new One());
    list.add(new Two());
    list.add(new Three());
    list.add(new Four());
    list.add(new Fieve());

}
class MyAdpter extends FragmentPagerAdapter
{

    public MyAdpter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

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

}

上一篇下一篇

猜你喜欢

热点阅读