nuggetbram
nuggetbram

Reputation: 345

Selected tab not being passed through to fragment in tablayout

In a simple tabLayout view viewPager setup I am unable to correctly pass through the selected tab to the fragment within it. As tabs are selected left to right (i.e tab 1 -> tab x) the tab is correctly interpreted, but as they are selected right to left, 0 is returned.

Here is the important code:

Activity including 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];
}
}

Fragment:

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;
}

The log method call in the onCreateView of the fragment will correctly return numbers 0->6 as the tabs are swiped through left to right, but as soon as a tab left of the current tab is selected, it will return 0, which will become the new origin (i.e one tab right will become 1)

Seems as though there is something going on with fragments coming in and out of focus that might be causing this?

Upvotes: 0

Views: 606

Answers (1)

Nir Patel
Nir Patel

Reputation: 367

First of all, you are passing pos - 1 in your new instance, because of which, your first tab will display log as -1. If you want correct value, only pass pos in newInstance. Other than that, make sure you are not passing any setOffscreenPageLimit in viewPager. Everthing else in your code seems to be okay. Let me know your exact issue if you are still facing it.

Upvotes: 0

Related Questions