Angus
Angus

Reputation: 12631

ViewPager - First fragment's onResume interfering with second fragment

I have an Activity "A" with a ViewPager (with TabLayout) inside. The viewPager includes 2 fragments "X" and "Y", since ViewPager handles the lifecycle of the fragments. When the activity is on resume, the fragments also go to resume.

When I launch the activity initially, the first tab - "X" fragment is in focus and displays the UI, during this I am getting a soft keyboard. (This keyboard is launched by spawning a mainUIThread with a delay of 1.5secs during the onResume of the "Y" fragment).

The question is, why does the onResume of "Y" fragment interfere while the "X" fragment's tab during onResume ? Is there a way to avoid it ?

I want to show the keyboard only for the "Y" fragment and not for the "X" fragment. Since the "Y" frament's onResume handles the keyboard somehow the keyboard gets visible.

Upvotes: 0

Views: 1152

Answers (2)

MiJey
MiJey

Reputation: 21

How about using OnPageChangeListener?

You can show the keyboard when Y fragment is selected, and hide the keyboard when other pages are selected.

my_view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
    override fun onPageSelected(position: Int) {
        if (position == yFragmentPosition) {
            showKeyboard()
        } else {
            hideKeyboard()
        }
    }
    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
    override fun onPageScrollStateChanged(state: Int) {}
})

Upvotes: 1

Ashish Sharma
Ashish Sharma

Reputation: 576

Both fragment onResume should be standalone and shouldn't affect the other one, but if this is happening, I can suggest you not to call fragment's on resume directly, instead use activity's onresume, there check for active fragment and, create resumeMethod which had all the things you need inside each fragment's onresume, and call active fragment's on resume, like fragmentA.resumeMethod() if fragment A is active, in this way you might avoid your error.

Upvotes: 1

Related Questions