Last active
November 17, 2022 06:56
-
-
Save cse-ariful/8b51eb5e18a13d5aae828d50816d9762 to your computer and use it in GitHub Desktop.
A Base Implementation of Fragment and is Very easy to work with fragments. Implemented most of the things you need on regular.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Bundle | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.activity.OnBackPressedCallback | |
import androidx.fragment.app.Fragment | |
import androidx.viewbinding.ViewBinding | |
typealias Inflate<T> = (LayoutInflater, ViewGroup?, Boolean) -> T | |
abstract class BaseFragment<V : ViewBinding>(private val inflater: Inflate<V>) : Fragment() { | |
private var _binding: V? = null | |
val binding: V get() = _binding!! | |
private val TAG = "BaseFragment" | |
open fun onBackPressed(params: OnBackPressedCallback) { | |
if (childFragmentManager.backStackEntryCount > 0) childFragmentManager.popBackStack() | |
else { | |
params.isEnabled = false | |
activity?.onBackPressedDispatcher?.onBackPressed() | |
params.isEnabled = true | |
} | |
} | |
override fun onCreateView( | |
inflaterp: LayoutInflater, | |
container: ViewGroup?, | |
savedInstanceState: Bundle? | |
): View? { | |
_binding = inflater.invoke(inflaterp, container, false) | |
_binding?.root?.setOnClickListener { } | |
return binding.root | |
} | |
abstract fun initView(savedInstanceState: Bundle?) | |
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
super.onViewCreated(view, savedInstanceState) | |
registerBackPress() | |
initView(savedInstanceState) | |
} | |
private val backPressCallback = object : OnBackPressedCallback(true) { | |
override fun handleOnBackPressed() { | |
onBackPressed(this) | |
} | |
} | |
private fun registerBackPress() { | |
activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, backPressCallback) | |
} | |
protected inline fun <reified T> grabListener(noinline onFind: ((it: T) -> Unit)? = null): T? { | |
var par = parentFragment | |
while (par != null) { | |
if (par is T) { | |
onFind?.invoke(par) | |
return par | |
} | |
par = par.parentFragment | |
} | |
if (activity is T) { | |
onFind?.invoke(activity as T) | |
return (activity as T) | |
} | |
return null | |
} | |
override fun onDestroy() { | |
super.onDestroy() | |
_binding = null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment