我有一个带有标签的活动。在活动的onCreate方法中,我有以下代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_team);
Intent i = getIntent();
myTeam = i.getParcelableExtra("TeamObject");
//MatchAsyncTask mat = new MatchAsyncTask()execute();
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarTeam);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ViewPager viewPager = (ViewPager) findViewById(R.id.vpTeam);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabsTeam);
tabLayout.setupWithViewPager(viewPager);
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar_team);
collapsingToolbar.setTitle(myTeam.getName());
ImageView img = (ImageView)findViewById(R.id.team_detail_header);
String strImg1 = "f"+String.valueOf(myTeam.getId());
int resId1 = getResources().getIdentifier(strImg1, "drawable", getPackageName());
img.setImageResource(resId1);
}
setWithViewPager函数的代码是:
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle args = new Bundle();
args.putInt("TeamId",myTeam.getId());
PlayerFragment pf = new PlayerFragment();
pf.setArguments(args);
InfoMatchFragment partidos = new InfoMatchFragment();
adapter.addFrag(pf, "Plantel");
adapter.addFrag(partidos, "Partidos");
viewPager.setAdapter(adapter);
}
ViewPager的适配器类是:
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
问题发生在我启动活动并且第一个片段加载到第一个选项卡上但是当我滑动到第二个选项卡时,显示了相同的片段。
感谢您的帮助。
答案 0 :(得分:0)
更改适配器方法并尝试此方法
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
PlayerFragment pf = new PlayerFragment();
//pf.setArguments(args);
return pf;
case 1:
return new InfoMatchFragment();
default:
return null;
}
}