0

I'm using a SlidingTabLayout (from the Google sources) in my app to navigate between different fragments. I can swipe between contents just fine, but the problem I'm facing is the title of the Action bar that is acting weird.

Suppose that I have two tabs with two titles ('First Title' and 'Second Title') :

| Action bar       |

| First Title | Second Title |

When I first enter the Fragment containing the SlidingTabLayout, the title of the Actionbar is like this :

| Firs...      |

| First Title | Second Title |

When I swipe (to the second tab for example), the title of the actionbar becomes :

| Second Title       |

| First Title | Second Title |

And stays like this. It seems that the Actionbar takes the title of the last Fragment loaded when I swipe at least once.

What I want is this :

I want to show a 'Main Title' in the Actionbar that never changes no matter what the title in the SlidingTabLayout is.

Here are some portions of my code:

** Fragment containing the SlidingTabLayout:

private String mainTitle;
....

@Override
public void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);

    // The mainTitle is given to this fragment by another fragment
    Bundle args = getArguments();
    if (args != null) {
        mainTitle = args.getString("TITLE");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.layout, container, false);
    mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
    mSlidingLayout = (SlidingTabLayout) rootView.findViewById(R.id.sliding_layout);
    List<Fragment> listFragments = new ArrayList<>();
    List<String> listTitles = new ArrayList<>();
    for (int i = 0; i < mSize; i++) {
        Bundle bundle = new Bundle();
        ....
        listFragments.add(Fragment.instanciate(getActivity(), CustomFragment.class.getName(), bundle));
        listTitles.add("...");
    }
    mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments, listTitles));

    mSlidingLayout.setDistributedEvenly(true);
    mSlidingLayout.setViewPager(mViewPager);

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    // I TRY TO SET THE TITLE HERE !!
    getActivity().getSupportActionBar().setTitle(mainTitle);
}

** Adapter:

class PagerAdapter extends FragmentPagerAdapter {
    List<Fragment> fragments;
    List<String> titles;
    ...
    @Override
    public Fragment getItem(int position) {
        Fragment fragment = fragments.get(position);
        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // maybe the problem is in this method.
        // this method is supposed to provide the titles for the tab
        // but maybe it's also changing the actionbar title
        return titles.get(position);
}

I'm setting the title of the ActionBar in the onResume method every time I enter a Fragment.

Thanks !

EDIT 1 :

I tried using the new SlidingTabLayout which I've got from the Google I/O, and the result is still the same !

It seems that the Title in the ActionBar is a hint at first, and then it changes to the last loaded fragment when I swipe to another fragment.

It's like it's loading fragment, and each time a fragment is loaded, the title in the ActionBar is overridden with the title of that fragment.

EDIT 2 :

I changed my code to post the latest version of it (I'm using now a SlidingTabLayout) and to show how I get my mainTitle.

Herve B
  • 195
  • 1
  • 15
  • what happens If you shorten your First Title? – Fadils Sep 22 '15 at 11:39
  • Same thing, I don't think it's a problem of the title's length, since it's showing "Second Title" when I swipe to another fragment. – Herve B Sep 23 '15 at 09:05
  • Why aren't you setting the title in the Activity's onCreate? – NasaGeek Sep 23 '15 at 15:09
  • Because basically my app has only one Activity and a lot of Fragments. And each time I change the Fragment, the title changes. I don't have one title per Activity... – Herve B Sep 23 '15 at 15:19

4 Answers4

1

you can use below code it works fine for me

public class MatchesActivity extends AppCompatActivity implements ActionBar.TabListener {

SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
FloatingActionButton skipButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_matches);
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowHomeEnabled(true);
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    skipButton = (FloatingActionButton) findViewById(R.id.skip_next);
    skipButton.setVisibility(View.GONE);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOffscreenPageLimit(1);
    mViewPager.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return false;
        }
    });
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    actionBar.addTab(
            actionBar.newTab().setText("MATCHES")
                    .setTabListener(this));
    actionBar.addTab(
            actionBar.newTab().setText("PINS")
                    .setTabListener(this));
    actionBar.addTab(
            actionBar.newTab().setText("CHATS")
                    .setTabListener(this));
}

@Override
public void onBackPressed() {
    startActivity(new Intent(MatchesActivity.this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK & Intent.FLAG_ACTIVITY_CLEAR_TOP));
    MatchesActivity.this.finish();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        onBackPressed();
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new MatchesFragment();
            case 1:
                return new PinsFragment();
            case 2:
                return new ConversationFragment();
            default:
                return new MatchesFragment();
        }
    }

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

    @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);
        }
        return null;
    }
}

}

Rax
  • 1,347
  • 3
  • 20
  • 27
  • I'm using a `PagerAdapter` and a `SlidingTabLayout` in a Fragment (and not an activity). It will be a little complicated to change all this... – Herve B Sep 23 '15 at 10:37
1

I am posting here a code of mine.It worked for me.Make required changes in it and try it.I used PagerSlidingTabStrip library in it.

public class DealFragment extends Fragment {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_deal, container, false);
    ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    viewPager.setAdapter(new SampleFragmentPagerAdapter(getChildFragmentManager()));
    PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip)view.findViewById(R.id.tabs);
    tabsStrip.setBackgroundColor(Color.parseColor("#333333"));
    // Attach the view pager to the tab strip
    tabsStrip.setViewPager(viewPager);
    return view;
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT = 2;
    private final String tabTitles[] = new String[] { "Today's Deals", "Deals Close By" };

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

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

    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        if(position==0)
        {
            return new TodaysDeal();
        }
        else
        {
            return new DealsCloseBy();
        }

    }

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles[position];
    }
}

}

hope it might help you.

Animesh Jena
  • 1,541
  • 1
  • 25
  • 44
  • Thanks Animesh, but I don't see where you set the title of the ActionBar. I only see where you set the titles of the tabs.. – Herve B Sep 23 '15 at 10:39
  • this will not appear as an ActionBar,it will appear below the action bar as a tabView , ActionBar or ToolBar,doesn't matter. and for the ActionBar name, you need n't have to specify here.It is based on the Activity name that you are mentioning at the manifest.xml of your app. – Animesh Jena Sep 23 '15 at 10:44
  • Well, actually the problem is the title in the **ActionBar**. In my app, the title of the ActionBar is set in the `onResume` method of Fragments. So the title changes every time we enter a new Fragment, and is not set in the manifest. And it's this title that changes weirdly when I use a Fragment with tabs... – Herve B Sep 23 '15 at 11:31
  • @HerveB:-But you can define it anyway by yourself. ActionBar ab=getSupportActionBar(); ab.setTitle("give your title name here"); – Animesh Jena Sep 23 '15 at 11:35
  • This is what I'm doing. See the `onResume` method in my Fragment. – Herve B Sep 23 '15 at 11:40
  • @HerveB:-remove it from onResume() and paste it in onCreateView(),it might work.Give it a try. – Animesh Jena Sep 23 '15 at 11:45
  • Thanks for the answer, but that doesn't work either :s – Herve B Sep 23 '15 at 12:00
1

The actionBar title doesn't change because onResume() is not called the time you swipe back.

It's because ViewPager doesn't call fragment's onResume the second time. Even though in reality the fragment is resumed.

What you can do is to move the setting of your actionbar title in your parent fragment (that contains pagertabstrip) to onCreateView instead.

For your reference:

** Fragment containing the PagerTabStrip:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.layout, container, false);
    mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);

    List<Fragment> listFragments = new ArrayList<>();
    List<String> listTitles = new ArrayList<>();

    ...

    // HERE's what you want
    final ActionBar actionBar = getActivity().getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(R.string.main_title);
    }

    mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments));

    return rootView;
}
Fadils
  • 1,508
  • 16
  • 21
  • Thanks Fadils, but it still doesn't work... **It seems that the Actionbar's title is overriden with the last Fragment loaded on the PagerAdapter** – Herve B Sep 23 '15 at 14:48
  • How do you get your mainTitle? Did you set the title with string resource as above? – Fadils Sep 23 '15 at 14:51
  • The title is given as a "String" object to the Fragment from another Fragment. So, I don't use a resource id, since the main Title can change – Herve B Sep 23 '15 at 15:13
  • Sorry if I'm mistaken, but you said the following. >What I want is this : I want to show a 'Main Title' in the Actionbar that never changes no matter what the title in the PagertabStip is.< So, now you want the title can be changed dynamically? Can you please update your question, along with how mainTitle is declared? – Fadils Sep 23 '15 at 15:17
  • Sorry, I didn't express myself right... What I wanted to say, is that this Fragment (which contains the tabs) can be accessed from different places, and each of these places will have it's own mainTitle, hense the mainTitle that can change. But when we're inside the Fragment itself, the mainTitle doesn't change ! I updated my question ! – Herve B Sep 23 '15 at 15:33
0

Found it !

It was really dumb of me (it explains why others didn't have this problem)

I was setting the title also in each of the Fragments (even those contained in the Tabs), so when I swiped, the onResume on those Fragments was called and it changed the title in the ActionBar...

Thank you all for the help, I appreciate it !

Herve B
  • 195
  • 1
  • 15