• 1000
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
replaceFragment(WordListFragment())
}
}
// Extension function to replace fragment
fun AppCompatActivity.replaceFragment(fragment: Fragment){
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.host,fragment)
transaction.addToBackStack(null)
transaction.commit()
}
Когда мы нажимаем на элементы, мы вызываем replaceFragment
внутри WordListAdapter
и go для другого фрагмента следующим образом:
class WordListAdapter : RecyclerView.Adapter<WordListAdapter.WordViewHolder>() {
...
override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
val current = words[position]
holder.wordItemView.text = current.word
holder.itemView.setOnClickListener {
// fire recyclerView click event
val activity = it.context as AppCompatActivity
val args = Bundle()
// Send string data as key value format
args.putString("word", current.word)
val fragment = WordDefinitionFragment()
fragment.arguments = args
activity.replaceFragment(fragment)
}
}
Мне просто интересно, правильный ли способ поместить replaceFragment
в onBindViewHolder
?