我有一个显示第n个项目的ViewPager和Tablayout。使用正确的页面标题填充选项卡,包含ViewPager的碎片显示正确的罚款,除非所选的选项卡未与ViewPager当前项目同步。
所选标签位置比viewpager当前项目的位置小1。这是Viewpager适配器。
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
@Override
public Fragment getItem(int position) {
Recipe selectedRecipe = getRecipeList().get(position);
return RecipeDetailFragment.newInstance(selectedRecipe.getId);
}
@Override
public int getCount() {
return .getRecipeList().size();
}
@Override
public CharSequence getPageTitle(int position) {
Recipe selectedRecipe = .getRecipeList().get(position);
String title = selectedRecipe.getTitle();
return title ;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
以下是我设置ViewPager的方法
private void setupViewPager() {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
答案 0 :(得分:1)
而不是在片段中使用静态变量,你可以使用, 下面的片段中的公共函数。
添加
@Override
public Fragment getItem(int position) {
Recipe selectedRecipe = getRecipeList().get(position);
RecipeDetailFragment receiptFRagment= new ReceiptFragment();
receiptFragment.setData(selectedRecipe.getId);
return receiptFragment;
}
而不是
@Override
public Fragment getItem(int position) {
Recipe selectedRecipe = getRecipeList().get(position);
return RecipeDetailFragment.newInstance(selectedRecipe.getId);
}
在片段中添加公共函数,
public void setData(int id){
this.id= id;
}
答案 1 :(得分:0)
最后,这就是我将ViewPager所选项目与Tablayout选中标签同步的方式。
void selectPage(final int pageIndex){
new Handler().postDelayed(
new Runnable() {
@Override public void run() {
tabLayout.setSmoothScrollingEnabled(true);
tabLayout.setScrollPosition(pageIndex, 0f, true);
}
}, 100);
}
然后我从两个地方调用此方法,首先是我设置Viewpager
recipePosition = getIntent().getIntExtra(Constants.RECIPE_POSITION, 0);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
if (recipePosition > 0){
recipePosition--;
}
viewPager.setCurrentItem(recipePosition,true);
selectPage(recipePosition);
然后在setItem中第二个
Recipe selectedRecipe = getRecipeList().get(position);
RecipeDetailFragment receiptFRagment= new ReceiptFragment();
receiptFragment.setData(selectedRecipe.getId);
selectPage(position);
return receiptFragment;
它的作品,我仍然无法理解为什么默认情况下这些不同步!