1

Consider there is an activity with a title. Viewpager fragment is inside the activity. Fragment will be loaded with data from network API.

Now I need to update the activity title after getting the data from API.

Problem:

  1. Since Viewpager is used, it loads the (prev), current, (next) fragments too. So activity is not aware of which title it is for.
  2. Each title is different for each fragment, so I need to update the title only when the user views that fragment.
Kamalakannan J
  • 2,818
  • 3
  • 23
  • 51

3 Answers3

0

In you Activity add the listener on ViewPager:

    viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {

            @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {

            }

            @Override public void onPageSelected(int position)
            {
                    //You can use switch case too
                    if (position== 0)
                    {
                          //set title
                    }
                    else if (position== 1)
                    {
                          //set title
                    }...
            }

            @Override public void onPageScrollStateChanged(int state)
            {

            }
        });
Akshay
  • 6,029
  • 7
  • 40
  • 59
0

You need to create object of your Activity, By using this Object you are able to use activity method.

For more detail; visit this link.How to use method from another Class?

Use this with addOnPageChangeListener method of pager, in it you will get your current postion of pager.

Bhoomika Patel
  • 1,895
  • 1
  • 13
  • 30
0

You can call the Activity method from Fragment by

  • Make method in Activity public
  • In fragment use getActivty() -> cast it to corresponding Activity then call this method

If you want to call Activity method only when fragment visible you can try https://stackoverflow.com/a/42019934/5381331

In Activity, you want to get the current visible fragment, you can try https://stackoverflow.com/a/47789367/5381331

Linh
  • 57,942
  • 23
  • 262
  • 279