Binding-managing fragment

PHOTO EMBED

Thu Jul 21 2022 07:33:38 GMT+0000 (UTC)

Saved by @gustavaa #kotlin #android

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import org.koin.android.ext.android.inject
import se.tv4.analytics.page.ScreenTracker

typealias FragmentInflater<T> = (LayoutInflater, ViewGroup?, Boolean) -> T

/**
 * base fragment to share the common functionality between the fragments in the app
 */
abstract class BaseFragment<T : ViewBinding>(private val inflate: FragmentInflater<T>) : Fragment() {

    private var _binding: T? = null

    /**
     * The view binding for this fragment.
     *
     * [https://developer.android.com/topic/libraries/view-binding]
     *
     * This property is only valid between [onCreateView] and [onDestroyView].
     */
    val binding: T
        get() = _binding ?: throw IllegalStateException("Cannot access view outside onCreateView and onDestroyView")

    @CallSuper
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = inflate(inflater, container, false)
        return binding.root
    }

    @CallSuper
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}
content_copyCOPY