在一个简单的tabLayout视图中,viewPager设置我无法正确地将选定的选项卡传递到其中的片段。当从左到右选择选项卡(即选项卡1 - >选项卡x)时,选项卡被正确解释,但是从右到左选择它们时,返回0。
以下是重要的代码:
活动包括tabLayout:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new OwnPagerAdapter(getSupportFragmentManager(), NavDrawer.this));
tabLayout.setupWithViewPager(viewPager);
PagerAdapter:
public class OwnPagerAdapter extends FragmentPagerAdapter {
private int TAB_COUNT = 7;
private String tabTitles[] = new String[] {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
private Context context;
public OwnPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public Fragment getItem(int position) {
return OwnTimetableFragment.newInstance(position - 1);
}
@Override
public int getCount() {
return TAB_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
片段:
public class OwnTimetableFragment extends Fragment {
public static final String ARG_DAY = "ARG_DAY";
private int mDay;
public static OwnTimetableFragment newInstance(int day) {
Bundle args = new Bundle();
args.putInt(ARG_DAY, day);
OwnTimetableFragment fragment = new OwnTimetableFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDay = getArguments().getInt(ARG_DAY);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View tabView = inflater.inflate(R.layout.fragment_own_timetable, container, false);
Log.e("mDay", mDay + "");
return tabView;
}
片段的onCreateView中的log方法调用将正确返回数字0-> 6,因为选项卡从左向右滑动,但只要选中当前选项卡左侧的选项卡,它将返回0 ,这将成为新的起源(即一个标签右边将成为1)
好像有些碎片进出焦点可能会引起这种情况?
答案 0 :(得分:0)
首先,您在新实例中传递 pos - 1 ,因此,您的第一个标签会将日志显示为-1。如果您想要正确的值,只需在newInstance中传递 pos 。 除此之外,请确保您没有在viewPager中传递任何setOffscreenPageLimit。在您的代码中覆盖其他似乎没问题。 如果你还在面对它,请告诉我你的具体问题。