我正在尝试创建一个具有三个可以线性访问的片段的活动。我想实现onBackPress方法,以便弹出顶部片段,并显示上一个片段。
package `in`.ac.bvmengineering.udaan2k19.Activity
import `in`.ac.bvmengineering.udaan2k19.Fragment.EventCategoryFragment
import `in`.ac.bvmengineering.udaan2k19.R
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
class EventActivity : AppCompatActivity() {
var fragment: Fragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_events)
switchFragment(EventCategoryFragment())
}
private fun switchFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction().add(R.id.event_frame, fragment,"Category").addToBackStack("Category").commitNow()
}
override fun onBackPressed() {
super.onBackPressed()
Toast.makeText(this,"${supportFragmentManager.backStackEntryCount}",Toast.LENGTH_LONG).show()
fragment = currentFragment()
when (fragment?.tag) {
"Category" -> finish()
"Events", "Details" -> supportFragmentManager.popBackStackImmediate(fragment?.tag, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
}
private fun currentFragment(): Fragment? {
return supportFragmentManager.findFragmentByTag(supportFragmentManager.getBackStackEntryAt(supportFragmentManager.backStackEntryCount-1).name)
}
}
但是每次我尝试弹出后退堆栈时,都会说后退堆栈为空 我尝试添加行
supportFragmentManager.beginTransaction().add(R.id.event_frame, fragment,"Category").addToBackStack("Category").commitNow()
但是它抛出了IllegealStateException:
java.lang.IllegalStateException: This transaction is already being added to the back stack