Search code examples
androidandroid-viewpagerfragmentpageradapterpagerslidingtabstrip

How to update view pager item TITLE dynamically


I have a simple messaging application module. In which, there are two swipable tabs. Received and Sent. Let us say I have 20 messages out of which 10 are unread. So what I am doing is showing the tabs as Received - (10). Now when I read the message, it marks the message as read. So I would like to change the title from Received - (10) to Received - (9).

Please let me know how can I do it?

Here is the code which I am using.

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

@Override
public CharSequence getPageTitle(int position) {

    if (position == 0) {
        // if position is zero, set the title to RECEIVED.
        return "Received" + " (" + String.valueOf(intUnreadReceivedMessagesCount) + ")";
    } else {
        // if position is 1, set the title to SENT.
        return "Sent";
    }
}

I am using Pager Sliding Tab Strip as a Pager Tab library. https://github.com/astuetz/PagerSlidingTabStrip

I have tried using notifyDataSetChanged() but for obvious reasons, it does not call it. Any way to resolve the issue. Any better alternative to show and update the count is also welcome.

Thank you.


Solution

  • It's just a guess without seeing the rest of your code.

    notifyDataSetChanged() should be working but there is a trick. You have to override one method in your adapter:

    public int getItemPosition(Object item) {
        return POSITION_NONE;
    }
    

    This way calling notifyDataSetChanged() will update currently visible page and it's neighbours.

    Without it, only new pages are updated.

    Update

    I looked at linked library. There is a public method notifyDataSetChanged() just like for adapter. So just assign an id for that PagerSlidingTabStrip inside XML and get a reference in your code. Then call:

    adapter.notifyDataSetChanged();
    tabStrip.notifyDataSetChanged();