Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put titles in ViewPager using fragments?

I am using ViewPager to allow user to swipe between fragments.

How can I add a the title of each fragment to the screen?

package com.multi.andres;

import java.util.List;
import java.util.Vector;

import com.viewpagerindicator.TitlePageIndicator;
import com.viewpagerindicator.TitleProvider;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class ViewPagerFragment extends FragmentActivity{

    private PagerAdapter mPagerAdapter; //contiene el pager adapter
    private static String[] titulosPaginas = { "APP 1", "APP 2" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.lcmeter); //layout que contiene el ViewPager

        initialisePaging(); //inicializo las paginas
    }

    private void initialisePaging() {

        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, FragmentPrueba1.class.getName()));
        fragments.add(Fragment.instantiate(this, FragmentPrueba2.class.getName()));
        this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager)super.findViewById(R.id.pager);
        pager.setAdapter(this.mPagerAdapter);

        //Agrega los titulos
        TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titulos);    //layout XML
        titleIndicator.setViewPager(pager);
    }

    /** *************************************************************************************************
    /** Clase:   public class PagerAdapter extends FragmentPagerAdapter implements TitleProvider
    /** Notas:   extends FragmentPagerAdapter permite el uso de las paginas de ViewPager pero con Fragments
    /**          implements TitleProvider permite el uso de los titulos en las paginas
    /** Funcion: crea paginas por las cuales deslizarse horizontalmente las cuales son usadas
    ****************************************************************************************************/
    public class PagerAdapter extends FragmentPagerAdapter implements TitleProvider {

        private List<Fragment> fragments;

        public String getTitle(int position) {
            // TODO Auto-generated method stub
            return titulosPaginas[position];    // titulo de la pagina
        }

        public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public int getCount() {
            return this.fragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

    }

}

But it doesn't show the titles of ViewPager and I don't know why. I used ViewPager with titles before but not with fragments and I cannot get titles working now.

like image 858
Andres Torti Avatar asked Apr 06 '12 00:04

Andres Torti


2 Answers

You can also use Jake Wharton's ViewPagerIndicator library to get the desired effect. Davek804's answer works too, but it requires you to reference the entire ActionBarSherlock library, which isn't as preferable if you only need a ViewPager that supports custom/styled titles.

Setting it up to work correctly is simply a matter of writing a tiny bit of XML, initializing your ViewPager in your Activity, and implementing a FragmentAdapter (which extends FragmentPagerAdapter implements TitleProvider) to specify which pages hold which Fragments.

  1. XML layout

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <com.viewpagerindicator.TabPageIndicator
            android:id="@+id/titles"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"/>
    
        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>
    
    </LinearLayout>
    
  2. Initialize in your Activity

    //Set the pager with an adapter
    ViewPager pager = (ViewPager)findViewById(R.id.pager);
    pager.setAdapter(new CustomAdapter(getSupportFragmentManager()));
    
    //Bind the title indicator to the adapter
    TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles);
    titleIndicator.setViewPager(pager);
    
  3. Implement a CustomFragmentAdapter

    public static class CustomFragmentAdapter extends FragmentPagerAdapter 
            implements TitleProvider {
    
            public static final int POSITION_PAGE_1 = 0;
            public static final int POSITION_PAGE_2 = 1;
            public static final int POSITION_PAGE_3 = 2;
    
            private static final String[] TITLES = new String[] { 
                "Title 1", 
                "Title 2", 
                "Title 3" 
            };
    
            public static final int NUM_TITLES = TITLES.length;
    
            public CustomFragmentAdapter(FragmentManager fm) {      
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {     
                switch (position) {
                case POSITION_TITLE_1:              
                    return PageOneFragment.newInstance();
                case POSITION_TITLE_2: 
                    return PageTwoFragment.newInstance();
                case POSITION_TITLE_3:
                    return PageThreeFragment.newInstance();         
                }
                return null;
            }
    
            @Override
            public int getCount() {
                return NUM_TITLES;
            }
    
            @Override
            public String getTitle(int position) {
                return TITLES[position % NUM_TITLES].toUpperCase();
            }
        }
    

Edit:

The ViewPagerIndicator library supports the titling features:

  1. TitlePageIndicator

    TitlePageIndicator

  2. TabPageIndicator

    TabPageIndicator

  3. CirclePageIndicator

    CirclePageIndicator

like image 157
Alex Lockwood Avatar answered Oct 12 '22 22:10

Alex Lockwood


Or if you don't like to use from third-part library, you can use support v4 PagerTabStrip class. For example:

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:layout_weight="1">
    <android.support.v4.view.PagerTabStrip
        android:id="@+id/pts_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</android.support.v4.view.ViewPager>

and in PagerAdapter override getPageTitle method:

public static class MyAdapter extends FragmentPagerAdapter  {
    ...
    @Override
    public CharSequence getPageTitle(int position) {
        return String.valueOf(position);
    }
}

You can access for xml element from code like this:

protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.pager);
    ...
    mAdapter = new MyAdapter(getSupportFragmentManager());
    // Add custom adapter
    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);

    // Get PagerTabStrip
    PagerTabStrip strip = (PagerTabStrip) findViewById(R.id.pts_main);
    strip.setDrawFullUnderline(false);
    ...

I hope it will helps for someone

like image 39
Ivvan Avatar answered Oct 13 '22 00:10

Ivvan