2
votes

I have a ViewPager with 3 tabs, in each of these tab I can have 2-3 or 4 sub tabs.

When opening the activity, all the tabs (all the fragments) are loaded. Some of the fragments are asking some permissions (can be same permission for different fragment).

My main problem is all the request permission pop up will be displayed when opening this activity. Event if the first fragment visible doesn't need any permission. Is there is a way to ask permission only when the fragment is visible? Or the only solution is to track the click on Tab and the ViewPager OnPageChangeListener?

2
That's how the ViewPager works. It will instantiate the first visible fragment, and a few on both sides - so if you have 3 fragments, all three will be instantiated,and they will all request their permissions if you're doing it in onCreateView() If you manage to change it's DEFAULT_OFFSCREEN_PAGES member from 1 to 0, you should get your desired effect I guess.Shark
Yes I know it is the purpose of the viewpager. Problem with offscreen page 0, my first page is a call to server, and navigate between page will make a call each time we go to first fragment... I was wondering if the view pager is giving use when page is shown, maybe I should use OnPageChangeListenerChol

2 Answers

0
votes

Override a method in all the fragments( except the First fragment ) ...

   @Override
   setUserVisibilityHint(...) {
    super..  
      if(getActivity()!=null) {

         requestPermissions();
      }
   }

1st time at the activity start it wont request permission because getActivity() is null for all the other fragments...from the 2nd time onwards...it will request permission..

Note :- It will request permission as soon as you swipe across your pages in the ViewPager.

0
votes

There is an argument visible. Use it to determine visibility.

override fun setUserVisibleHint(visible: Boolean) {
    super.setUserVisibleHint(visible)
    if (visible && activity != null) {
        checkPermissions()
    }
}