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.
A fragment is not required to be a part of the Activity layout ; you may also use a fragment without its own UI as an invisible worker for the Activity but it needs to be attached to an Activity in order to appear on the screen. Save this answer.
ViewPager in Android allows the user to flip left and right through pages of data. In our android ViewPager application we'll implement a ViewPager that swipes through three views with different images and texts.
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));
}
}
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With