How to add page title and icon in android FragmentPagerAdapter
Asked Answered
M

5

16

I want to display title with respective icon in with header page title. like below image, however only able to display title and missing icon.

Here is the my sample code,.

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.

        Log.e("POSITION", "position=" + position);
        Fragment fragment;
        switch (position) {
        case 0:
         //Fragment1
        case 1:
         //Fragment2
        case 2:
         //Fragment3
        case 3:
         //Fragment4
        case 4:
         //Fragment5

        }
        return null;

    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

    // using both these techniques but could not get icon in title
    /*
     * public int getIconResId(int index) { return ICONS[index % ICONS.length]; }
     */

    public int getPageIconResId(int position) {
        return ICONS[position];
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
        return getString(R.string.title_section1).toUpperCase(l);
        case 1:
        return getString(R.string.title_section2).toUpperCase(l);
        case 2:
        return getString(R.string.title_section3).toUpperCase(l);
        case 3:
        return getString(R.string.title_section4).toUpperCase(l);
        case 4:
        return getString(R.string.title_section5).toUpperCase(l);
        }
        return null;
    }

    }

and in onCreate:

mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

Using this xml file for display fragment page adapter in fragment;

<android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rlv2"
        android:layout_marginTop="-30dp" >

        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/pager_title_strip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="4dp"
            android:paddingTop="4dp"  
            android:textColor="@color/black"
            android:textStyle="bold" />
    </android.support.v4.view.ViewPager>

Output image that i need my app.Could you please any idea how to display section page adapter with icon and title.

enter image description here

Monaghan answered 7/7, 2015 at 5:27 Comment(0)
M
21

I got solution from Stever.

Drawable myDrawable;
String title;

@Override
public CharSequence getPageTitle(int position) {
   switch (position) {
    case 0:
       myDrawable = getResources().getDrawable(R.drawable.img_section1);
       title = getResources().getString(R.string.title_section1);
       break;
    case 1:
       myDrawable = getResources().getDrawable(R.drawable.img_section2);
       title = getResources().getString(R.string.title_section2);
       break;
    case 2:
       myDrawable = getResources().getDrawable(R.drawable.img_section3);
       title = getResources().getString(R.string.title_section3);
       break;
    case 3:
       myDrawable = getResources().getDrawable(R.drawable.img_section4);
       title = getResources().getString(R.string.title_section4);
       break;
    case 4:
       myDrawable = getResources().getDrawable(R.drawable.img_section5);
       title = getResources().getString(R.string.title_section5);
       break;
    default:
      //TODO: handle default selection
       break;
    }

    SpannableStringBuilder sb = new SpannableStringBuilder("   " + title); // space added before text for convenience
    try {
        myDrawable.setBounds(5, 5, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(myDrawable, DynamicDrawableSpan.ALIGN_BASELINE);
        sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    } catch (Exception e) {
        // TODO: handle exception
    }

Thank you stever.

Monaghan answered 7/7, 2015 at 6:27 Comment(3)
getResources() get be called.Emaciation
Also see https://mcmap.net/q/540563/-display-icons-on-fragmentpageradapter-tabs if not working to due to caps of text.Personalism
how to do this ,i have created selector with 2 images per tab. when i select a tab, my image color will be white with selected state in selector, else image is default black colored. i tried it in above myDrawable. but its not worked.Doordie
O
27

If you are using the design support library TabLayout, you can simply call:

tabLayout.getTabAt(i).setIcon();
Oly answered 23/1, 2016 at 21:16 Comment(4)
this answer does the job well and saved time. Thanks.Leahy
Call but where? I am using a TabLayout and none of the answers is working, If you call this in bindViewPager then you will get a null reference error. Can you please update your answer within the class of ActionsAdapter as @Dharma did?Tailing
This is the way, HOWEVER, there is some bug in Tablayout/ViewPager in that icons are removed after a fragment refresh. Need to reinsert them each time.Aftershock
if getting NullPointer just use ExecutorService with Handler - you are trying setIcon() before tabs really drawed / createdReticule
M
21

I got solution from Stever.

Drawable myDrawable;
String title;

@Override
public CharSequence getPageTitle(int position) {
   switch (position) {
    case 0:
       myDrawable = getResources().getDrawable(R.drawable.img_section1);
       title = getResources().getString(R.string.title_section1);
       break;
    case 1:
       myDrawable = getResources().getDrawable(R.drawable.img_section2);
       title = getResources().getString(R.string.title_section2);
       break;
    case 2:
       myDrawable = getResources().getDrawable(R.drawable.img_section3);
       title = getResources().getString(R.string.title_section3);
       break;
    case 3:
       myDrawable = getResources().getDrawable(R.drawable.img_section4);
       title = getResources().getString(R.string.title_section4);
       break;
    case 4:
       myDrawable = getResources().getDrawable(R.drawable.img_section5);
       title = getResources().getString(R.string.title_section5);
       break;
    default:
      //TODO: handle default selection
       break;
    }

    SpannableStringBuilder sb = new SpannableStringBuilder("   " + title); // space added before text for convenience
    try {
        myDrawable.setBounds(5, 5, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(myDrawable, DynamicDrawableSpan.ALIGN_BASELINE);
        sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    } catch (Exception e) {
        // TODO: handle exception
    }

Thank you stever.

Monaghan answered 7/7, 2015 at 6:27 Comment(3)
getResources() get be called.Emaciation
Also see https://mcmap.net/q/540563/-display-icons-on-fragmentpageradapter-tabs if not working to due to caps of text.Personalism
how to do this ,i have created selector with 2 images per tab. when i select a tab, my image color will be white with selected state in selector, else image is default black colored. i tried it in above myDrawable. but its not worked.Doordie
S
1

for me it worked like this :

@Override
    public CharSequence getPageTitle(int position) {
        SpannableStringBuilder sb;
        ImageSpan span;
        switch (position) {
            case 0:
                myDrawable = getResources().getDrawable(R.drawable.heart_18);
                sb = new SpannableStringBuilder("  Page1"); // space added before text for convenience

                myDrawable.setBounds(0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
                span = new ImageSpan(myDrawable, ImageSpan.ALIGN_BASELINE);
                sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                return sb;
            case 1:
                myDrawable = getResources().getDrawable(R.drawable.star_grey_18);
                 sb = new SpannableStringBuilder("  Page2"); // space added before text for convenience

                myDrawable.setBounds(0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
                span = new ImageSpan(myDrawable, ImageSpan.ALIGN_BASELINE);
                sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                return sb;
            case 2:
                myDrawable = getResources().getDrawable(R.drawable.star_pink_18);
                sb = new SpannableStringBuilder("  Page3"); // space added before text for convenience

                myDrawable.setBounds(0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
                span = new ImageSpan(myDrawable, ImageSpan.ALIGN_BASELINE);
                sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                return sb;
        }
    }
}

enter image description here

Slur answered 25/4, 2016 at 5:24 Comment(1)
Hi, Its not working with TabLayout, how can i make this work?Tailing
L
1

you can use :

myTabLayout.getTabAt(index).setIcon(R.drawable.myIcon);
Lothar answered 19/3, 2020 at 16:5 Comment(0)
D
0

Find solve here

Create icon array like this private int[] tabIcons = { R.drawable.ic_tab_favourite, R.drawable.ic_tab_call, R.drawable.ic_tab_contacts};

and setIcon to tabLayout

tabLayout = (TabLayout) findViewById(R.id.tabs);

tabLayout.getTabAt(0).setIcon(tabIcons[0]); tabLayout.getTabAt(1).setIcon(tabIcons[1]); tabLayout.getTabAt(2).setIcon(tabIcons[2]);

more here

Link1 :https://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

Link 2 :http://www.androiddeft.com/tablayout-viewpager-android/

Dewyeyed answered 17/6, 2019 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.