我正在创建带有片段的底部导航视图,但问题是当我按下返回时什么也没有发生,但是当我再次按下时,我的片段发生了变化。我正在使用 .addToBackStack
但它可以使用 2 次返回。
这是我的代码的参考
提前致谢
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.ikgptu.stookptu.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//Frag Instance
val homeFragment = HomeFragment()
val notesFragment = NotesFragment()
val expenseFragment = ExpenseFragment()
val printFragment = PrintFragment()
setCurrentFragment(homeFragment)
binding.bottomNavbar.setOnNavigationItemSelectedListener{
when(it.itemId) {
R.id.menu_home -> {
setCurrentFragment(homeFragment)
}
R.id.menu_notes -> {
setCurrentFragment(notesFragment)
}
R.id.menu_expense ->{
setCurrentFragment(expenseFragment)
}
R.id.menu_print ->{
setCurrentFragment(printFragment)
}
}
true
}
}
private fun setCurrentFragment(fragment: Fragment){
supportFragmentManager.beginTransaction().apply {
replace(R.id.fragContainer,fragment).addToBackStack(null)
commit()
}
}
}