Search code examples
androidfragmentbottom-sheetbottomsheetdialogfragment

java.lang.IllegalStateException: view not added


I am getting the below exception. Couldn't understand why. Tried to reproduce the issue too.But couldn't succeed. Can someone help me understand why am I getting the issue and how to resolve it. Its not occuring all the time too.

Fatal Exception: java.lang.IllegalStateException: view not added
       at com.android.internal.policy.PhoneWindow.getViewRootImpl(PhoneWindow.java:1851)
       at com.android.internal.policy.PhoneWindow.setLocalFocus(PhoneWindow.java:1835)
       at com.qikwork.worker.views.fragment.MyBottomSheetFragment$onCreateView$1.onShow(MyBottomSheetFragment.java:53)
       at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java:1465)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loop(Looper.java:233)
       at android.app.ActivityThread.main(ActivityThread.java:7212)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

Code is as below:

class MyBottomSheetFragment() : BottomSheetDialogFragment(), ClockStatusBroadCastListener { ...

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.my_bottomsheet,
        container,
        false
    )

    dialog!!.setOnShowListener { dia ->
        val bottomSheetDialog = dia as BottomSheetDialog
        val bottomSheetInternal: FrameLayout =
            bottomSheetDialog.findViewById(com.google.android.material.R.id.design_bottom_sheet)!!
        val bottomSheetBehaviour = BottomSheetBehavior.from(bottomSheetInternal)
        bottomSheetBehaviour.state = BottomSheetBehavior.STATE_EXPANDED
        bottomSheetInternal.layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT
        bottomSheetDialog.window?.setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN or
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
        )
        bottomSheetDialog.window?.setLocalFocus(true, true)
    }
    return binding.root
}.....

Line no 53 points to R.layout.my_bottomsheet


Solution

  • Using the setLocalFocus(true, true) is causing the issue.Removing that worked.