0

我有一个启用拖放功能的回收站视图。

当我重新排序项目时,我试图保存项目的交换位置。

这是我的 ontouch 监听器。

override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                // Notify your adapter that an item is moved from x position to y position
                mOrderChanged = true
                val from = viewHolder.absoluteAdapterPosition
                val to = target.absoluteAdapterPosition
                updatePos.invoke(
                    UpdatePos(
                        fromId = cps[from].id,
                        fromPos = from,
                        toId = cps[to].id,
                        toPos = to
                    )
                )

updatePos是一个监听器,监听器触发片段中的以下代码。

{ updateData ->

                        vm.swapCpPosition(
                            updateData.fromId, updateData.fromPos, updateData.toId, updateData.toPos
                        )


                }

swapCpPosition看起来像这样

fun swapCpPosition(fromID : Long,fromPos:Int,toID:Long,toPos:Int){
        viewModelScope.launch {
            dailyChartRepo.swapCpPosition(fromID, fromPos, toID, toPos)
        }
    }

dailyChartRepo.swapCpPosition在回购中:

suspend fun swapCpPosition(fromID : Long,fromPos:Int,toID:Long,toPos:Int){
      dailyChartDao.swapCpPosition(fromID,fromPos,toID,toPos)

  }

dailyChartDao.swapCpPosition在道:

 @Query("update cp_view_group set position =:pos where cp_id=:cpID")
    fun setCpPosition(pos: Int, cpID: Long){
        Timber.i("room: pos $pos id $cpID")
    }

    @Transaction
    suspend fun swapCpPosition(fromID: Long, fromPos: Int, toID: Long, toPos: Int) {
        setCpPosition((toPos+1), fromID)
        setCpPosition((fromPos+1), toID)
    }

查询正在根据日志执行

2021-10-25 12:26:58.368 26091-26180/in_.co.iptech.purusharth I/mpurusharth_DailyChartDaoNew$DefaultImpls: room: pos 1 id 1633341941324
2021-10-25 12:26:58.369 26091-26180/in_.co.iptech.purusharth I/mpurusharth_DailyChartDaoNew$DefaultImpls: room: pos 2 id 17

在列表中 id17是第一项,id1633341941324是初始项目位置。

然而,位置值没有保存在数据库中,id 的位置17仍然是1id 1633341941324仍然是数字 2 在此处输入图像描述

我错过了什么,为什么值没有更新?

4

1 回答 1

0

这是插入你的模型

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertData(data: yourModel)

获取要更新的项目)

@Query("select * from table where id=:id")
suspend fun getData(id: Int): your model?

然后使用事务和更新

@Transaction
suspend fun updateData(id: Int, name:String) {
    val data: yourModel? = getData(id)
    if (data!= null) {
        data.title= name
        insertData(data)
    }
}
于 2021-10-26T10:13:08.920 回答