Dynamically change ViewPagerIndicator titles

2020-07-17 15:22发布

问题:

My current project uses some ListFragments to show rows of data. The rows get updated dynamically every some seconds. The amount of rows varies with every update and in every ListFragment.

I would like to show the amount of rows to the user, and think that the perfect place for that would be next to the Fragment's title in the ViewPagerIndicator. I provided a sample image for better comprehension:

Sadly I am pretty clueless how to achieve this. I tried the following:

public class PagerAdapter extends FragmentPagerAdapter {
    private int numOne = 0;
    private int numTwo = 0;

    // ...

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
        case 0:
            return "List 1 (" + numOne + ")";
        case 1:
            return "List 2 (" + numTwo + ")";
        default:
            return "";
    }

    public void setNumOne(int num) {
        this.numOne = num;
    }

    public void setNumTwo(int num) {
        this.numTwo = num;
    }
}

When I now call the setNumXXX() method, nothing happens, until I move between fragments, what seems to trigger the getPageTitle() to fire.

My question is: How can I force an update of the title(s), everytime when the num value changes?

回答1:

If you call notifyDataSetChanged() on the indicator instance it will redraw itself and grab the new titles.