0

I created five fragments inside the view pager.

All fragments are created as the activity containing the viewpager is executed.

Therefore, the method of the fragment is executed as soon as the activity is executed.

In other parts this is what I intended.

However, this method raises another activity via Intent, which I did not want.

The point at which I want this method to execute is when the fragment is put on the screen.

Is there a method that works when a fragment inside the view pager that is already created is displayed on the screen?

The general life cycle method of a fragment can not be used because it works concurrently with activity execution.

If you know of any way I can use it, I would be grateful to let you know.

Have a good day :)

Jshin
  • 131
  • 2
  • 9

2 Answers2

2

Override this method in fragment

@Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        //if fragment is visible then menuVisible = true else false
    }
theanilpaudel
  • 3,348
  • 8
  • 39
  • 67
1

Please Implement this P.S It's in Kotlin it will be almost the same for jAVA

viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
        override fun onPageScrollStateChanged(state: Int) {}
        override fun onPageScrolled(position:Int,positionOffset:Float,positionOffsetPixels: Int) {}
        override fun onPageSelected(position: Int) {
            when (position) {}
        }
    })
  • thank you! But I solved it with setMenuVisibility in order to get it inside the fragment. thank you for your reply. have a nice day :) – Jshin Oct 24 '18 at 06:25
  • 1
    by using @theanilpaudel 's answer u need to override that method in all your fragments!! if u use Parthiv Mistri 's answer then u just need to add page change listener on Activity, in onPageselected u can get the fragment's object by viewpager.getItem(position) hence u can utilize it that way – Akash Dubey Oct 24 '18 at 09:57