Search code examples
androidandroid-fragmentsandroid-permissions

Views from old fragment remain in content view after the fragment is replaced


I have came across a peculiar bug : in my application I have bottom navigation bar that replaces the fragments in FrameLayout view using a following piece of code:

override fun setFragment(frag: Fragment, addToBackStack: Boolean) {
    FirebaseAnalytics.getInstance(this).setCurrentScreen(this, frag::class.java.simpleName, frag::class.java.simpleName)
    val ft = supportFragmentManager.beginTransaction()
            .setCustomAnimations(R.anim.fragment_in, R.anim.fragment_out, R.anim.fragment_in, R.anim.fragment_out)
            .replace(R.id.container, frag)

    if (addToBackStack) {
        viewModel.showNavigation = false
        ft.addToBackStack(null)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    ft.commit()
}

Everything seems to work fine - but for a one fragment in which in onCreateView method I call the following method:

override fun requestPermissions(permissions: Array<String>, requestCode: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        activity.requestPermissions(permissions, requestCode)
}

This causes the view from the previous fragment to remain on screen and new fragment to be added below them, as seen in the screenshot:

screenshot

What's worse, the views will stay in the screen until the activity is killed. The only workaround I was able to find was adding a 0,5 second delay before asking for permission:

Handler().postDelayed({ requestPermission(android.Manifest.permission.ACCESS_FINE_LOCATION, requestCode = REQUEST_PERMISSION_LOCATION) }, 500L)

My question is - does anyone know what is the cause of this behaviour and if there's a better way to circumvent it?


Solution

  • The solution for me was to set the background color in the xml file as suggested in the original question comments by @Yolo.

    android:background="@android:color/white"
    

    After I made this change, pieces of this fragment didn't hang around anymore when I switched to new fragments.