我需要在数周和数天内实现计划编辑功能。在应用中,计划的每一天都是Fragment
内的ViewPager
。现在,我尝试将所选项目存储在特殊类的主机Activity
中:
class LessonEditor {
var mode: Mode = Mode.NONE
private set(value) {
field = value
callbacks.forEach(fun(item: Callback) {
item.onChangeEditMode(value)
})
}
private var callbacks: MutableList<Callback> = mutableListOf()
private var editList: MutableList<Int>? = null
private var createList: MutableList<CreateItem>? = null
fun create() {
editList = mutableListOf()
createList = mutableListOf()
callbacks.forEach(fun(item: Callback) {
item.onCreateEditor()
})
}
fun destroy() {
callbacks.forEach(fun(item: Callback) {
item.onDestroyEditor()
})
editList?.clear()
createList?.clear()
editList = null
createList = null
mode = Mode.NONE
}
fun add(id: Int): Boolean {
when (mode) {
Mode.CREATE -> return false
Mode.NONE -> mode = Mode.EDIT_ONE
Mode.EDIT_ONE -> mode = Mode.EDIT_FEW
else -> {}
}
return editList?.add(id)?: false
}
fun subscribe(callback: Callback) {
callbacks.add(callback)
}
fun unsubscribe(callback: Callback) {
callbacks.remove(callback)
}
fun add(week: Int, day: Day, order: Int): Boolean {
if (Mode.EDIT_ONE == mode || Mode.EDIT_FEW == mode) {
return false
}
if (Mode.NONE == mode) {
mode = Mode.CREATE
}
return createList?.add(CreateItem(week, day, order))?: false
}
fun remove(id: Int) {
if (Mode.NONE == mode || Mode.CREATE == mode) {
return
}
if (editList?.remove(id) == true) {
if (editList?.isEmpty() == true) {
mode = Mode.NONE
} else if (1 == editList?.size) {
mode = Mode.EDIT_ONE
}
}
}
fun remove(week: Int, day: Day, order: Int) {
if (Mode.CREATE != mode) {
return
}
if (createList?.remove(CreateItem(week,day, order)) == true &&
createList?.isEmpty() == true) {
mode = Mode.NONE
}
}
data class CreateItem(var week: Int, var day: Day, var order: Int)
enum class Mode {
NONE, CREATE, EDIT_ONE, EDIT_FEW
}
interface Callback {
fun onCreateEditor()
fun onDestroyEditor()
fun onChangeEditMode(mode: Mode)
}
}
这是一个草稿模型。主要思想是主要活动控制着LessonEditor
的生命周期,并且Fragment
s可以从实现LessonEditor.Callback
的编辑器中进行订阅和退订。但是我的解决方案并不方便,因为我需要复制数据,因为Fragment
需要将适配器的数据保存在savedInstanceState
中,并且当用户再次选择该片段时,它需要与之同步状态LessonEditor
。
是否有一些更优雅的方式可以通过片段进行编辑?