fix crash when ViewControllerFragment is used in ViewPager

This commit is contained in:
Sergey Vlasenko 2024-04-08 12:19:28 +03:00
parent 447902ae07
commit 3150297590
1 changed files with 16 additions and 10 deletions

View File

@ -35,6 +35,7 @@ import android.view.animation.Animation
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import ru.touchin.roboswag.core.utils.ShouldNotHappenException
import ru.touchin.roboswag.navigation_viewcontroller.BuildConfig
import ru.touchin.roboswag.navigation_viewcontroller.viewcontrollers.ViewController
@ -80,7 +81,8 @@ open class ViewControllerFragment<TActivity : FragmentActivity, TState : Parcela
lateinit var state: TState private set
lateinit var viewControllerClass: Class<ViewController<TActivity, TState>> private set
var viewControllerClass: Class<ViewController<TActivity, TState>>? = null
private set
private var viewController: ViewController<out TActivity, out TState>? = null
@ -241,15 +243,19 @@ open class ViewControllerFragment<TActivity : FragmentActivity, TState : Parcela
creationContext: ViewController.CreationContext,
savedInstanceState: Bundle?
): ViewController<out TActivity, out TState> {
if (viewControllerClass.constructors.size != 1) {
throw IllegalStateException("There should be single constructor for $viewControllerClass")
}
val constructor = viewControllerClass.constructors[0]
return when (constructor.parameterTypes.size) {
1 -> constructor.newInstance(creationContext)
2 -> constructor.newInstance(creationContext, savedInstanceState)
else -> throw IllegalArgumentException("Wrong constructor parameters count: ${constructor.parameterTypes.size}")
} as ViewController<out TActivity, out TState>
viewControllerClass
?.let { mViewControllerClass ->
if (mViewControllerClass.constructors.size != 1) {
throw IllegalStateException("There should be single constructor for $viewControllerClass")
}
val constructor = mViewControllerClass.constructors[0]
return when (constructor.parameterTypes.size) {
1 -> constructor.newInstance(creationContext)
2 -> constructor.newInstance(creationContext, savedInstanceState)
else -> throw IllegalArgumentException("Wrong constructor parameters count: ${constructor.parameterTypes.size}")
} as ViewController<out TActivity, out TState>
}
?: throw ShouldNotHappenException("viewControllerClass is null")
}
override fun toString(): String = "${super.toString()} ViewController: $viewControllerClass"