Android Studio default "Tabbed Activity", how to swipe through fragments?
Asked Answered
B

2

10

Complete beginner here..

I have used the "Tabbed Activity" default from the New Project Wizard.

I am trying to get it to swipe through 3 different fragments, however I simply cant see where to tell the program to do it. Do I load them in as an array, if yes where should I do it and how do I instantiate the different fragments?

Any pointers and/or solutions is very appreciated.

Browse answered 5/8, 2014 at 14:24 Comment(0)
V
3

you can create a pager adapter from where you can call fragments based on tabs.

public class TabsPagerAdapter extends FragmentPagerAdapter {

public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        // Top Rated fragment activity
        return new TopRatedFragment();
    case 1:
        // Games fragment activity
        return new GamesFragment();
    case 2:
        // Movies fragment activity
        return new MoviesFragment();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return 3;
}

}

and initialize the tabs values in onCreate method of main activity to get tabs working

private String[] tabs = { "Top Rated", "Games", "Movies" };
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

    // Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

}

Vouch answered 11/8, 2015 at 12:8 Comment(0)
N
1

I know that this question is old, but hopefully it can help someone. This was really frustrating for me as well since I'm trying my best to learn Android but the wizard seems to have provided an incomplete template.

Anyways,

In fragment_main.xml, add some text to the TextView and the pages will show up now that there's content.

<TextView android:id="@+id/section_label" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hello World" />
Nocturnal answered 10/7, 2015 at 6:42 Comment(1)
I found this helpful but it would be a good answer (it doesn't really answer the questions asked) if you fleshed this out with more detail with the knowledge that you've now presumably gained.Rey

© 2022 - 2024 — McMap. All rights reserved.