Implementing sliding tabs in a fragment

I am looking at a tutorial on using TabLayout. This is how they show to attach the PagerAdapter class.

public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get the ViewPager and set it PagerAdapter so that it can display items
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(), 
        MainActivity.this));

    // Give the TabLayout the ViewPager
    TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setupWithViewPager(viewPager);
}

      

However their TabLayout is in Activity and mine is in Fragment. I am having trouble adapting their code to my use case because I don't quite understand the practical differences between Activities and Fragments. Right now, when I try to swipe between the tabs, nothing happens. Here is my code:

public class CandidateListFragment extends Fragment {
public static final String TAG = "candidates";

@InjectView(R.id.tabLayout) TabLayout tabLayout;

public CandidateListFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_candidatelist, container, false);
    initInstances(v);
    return v;
}

private void initInstances(View v){
    //TODO: Change to support below API level 21
    getActivity().findViewById(R.id.toolbar_actionbar).setElevation(R.dimen.toolbar_candidatelist_elevation);
    ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
    viewPager.setAdapter(new TabsFragmentPagerAdapter(getActivity().getSupportFragmentManager(),
            getActivity()));
    ButterKnife.inject(this, v);
    tabLayout.setupWithViewPager(viewPager);
}

@Override public void onDestroyView() {
    super.onDestroyView();
    ButterKnife.reset(this);
}

      

+3


source to share


1 answer


I understood that!!! I had the xml layout file for the fragment set to a RelativeLayout and not a LinearLayout, so my ViewPager was not on the screen, which meant I couldn't swipe. These are the simple mistakes that make me



+3


source







All Articles