Skip to content

Instantly share code, notes, and snippets.

@dmitriy-chernysh
Last active August 29, 2015 14:24
Show Gist options
  • Save dmitriy-chernysh/a55cc4e0917a875dbea4 to your computer and use it in GitHub Desktop.
Save dmitriy-chernysh/a55cc4e0917a875dbea4 to your computer and use it in GitHub Desktop.
Android ViewPager adapter
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
pagerAdapter.addPage( /*new fragment here*/ , /*title here*/);
pagerAdapter.addPage(/*new fragment here*/, /*title here*/);
//etc.
ViewPager viewPager = (ViewPager) findViewById(/*view pager*/);
viewPager.setAdapter(pagerAdapter);
<android.support.design.widget.CoordinatorLayout
android:id="@+id/coordinatorLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- toolbar -->
...................................
<!-- tab layout -->
...................................
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
package study.android.coordinatorlayout.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> mFragmentList = new ArrayList<>();
private ArrayList<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
/**
* Method for adding new ViewPage
* @param fragment Fragment
* @param title String
*/
public void addPage(Fragment fragment, String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment