In MainActivity
fun replaceFragment(fragment: Fragment, tag: String) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment, tag).addToBackStack("").commit()
}
In FragmentTwo
class FragmentTwo:Fragment(){
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
//your code
}
companion object {
val TAG = FragmentTwo::class.java.simpleName
@JvmStatic
fun newInstance() = FragmentTwo()
}
}
In FragmentOne
class FragmentOne:Fragment(){
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
//your code
}
fun onItemSelected(){
val frag=FragmentTwo.newInstance()
(activity as MainActivity).replaceFragment(frag,FragmentTwo.TAG)
}
companion object {
val TAG = FragmentOne::class.java.simpleName
@JvmStatic
fun newInstance() = FragmentOne()
}
}
В классе адаптеров :
itemView.setOnClickListener{
frag.onItemSelected()
}