Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
Bhargav Jhaveri Avatar asked Aug 07 '14 20:08

Bhargav Jhaveri


2 Answers

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();
like image 87
Damian Petla Avatar answered Oct 07 '22 16:10

Damian Petla


Accepted answer didn't work for me, using a custom PagerAdapter, and android.support.design.widget.TabLayout for the tabs.

This worked for me:

private void refreshTabTitles() {
    for (int i = 0; i < adapter.getCount(); i++) {
        Tab tab = tabs.getTabAt(i);
        if (tab != null) {
            tab.setText(adapter.getPageTitle(i));
        }
    }
}
like image 27
marmor Avatar answered Oct 07 '22 14:10

marmor