我通过向右或向左滑动屏幕来用动画更改片段。 这是父片段:
class StatsFragment: Fragment() {
private lateinit var tvSortCategories: TextView
private lateinit var tvSortMonths: TextView
private var x: Float? = null
private val fragmentStatsCat = StatsCategoryFragment()
private val fragmentStatsMon = StatsMonthFragment()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.fragment_stats, container, false)
tvSortCategories = view.findViewById(R.id.tvStatsCategories)
tvSortMonths = view.findViewById(R.id.tvStatsMonths)
tvSortCategories.isSelected = true
tvSortCategories.setOnClickListener {
inflateCategory()
}
tvSortMonths.setOnClickListener {
inflateMonth()
}
childFragmentManager.beginTransaction()
.replace(R.id.stats_container, fragmentStatsCat)
.commit()
view.setOnTouchListener {_, event ->
when(event.action) {
MotionEvent.ACTION_DOWN -> {
x = event.x
}
MotionEvent.ACTION_MOVE -> {
if(x != null) {
val dx = event.x - x!!
if(dx > 200f) {
inflateCategory()
x = event.x
}
if (dx < -200f) {
inflateMonth()
x = event.x
}
}
}
}
true
}
return view
}
private fun inflateCategory() {
tvSortCategories.isSelected = true
tvSortMonths.isSelected = false
childFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.stats_container, fragmentStatsCat)
.commit()
}
private fun inflateMonth() {
tvSortCategories.isSelected = false
tvSortMonths.isSelected = true
childFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.replace(R.id.stats_container, fragmentStatsMon)
.commit()
}
}
这很好,但有一个例外。当我执行fragmentTransaction时,虽然旧的fragmentTransaction尚未完成,但它崩溃并显示“ java.lang.IllegalStateException”:“必须在所有者的初始化阶段才创建重新启动器”
有没有办法可以在执行新交易之前检查旧交易是否已完成?
编辑:进一步解释我到底想做什么:
我想在两个子片段之间切换,方法是将信条滑过另一个片段,或者触摸“按类别/月排序”。