implementing initial drag & drop

This commit is contained in:
tibbi 2022-09-21 23:25:17 +02:00
parent f86caa6c89
commit 9fba3b56d6
3 changed files with 31 additions and 3 deletions

View File

@ -20,6 +20,9 @@ interface HomeScreenGridItemsDao {
@Query("UPDATE home_screen_grid_items SET title = :title WHERE package_name = :packageName") @Query("UPDATE home_screen_grid_items SET title = :title WHERE package_name = :packageName")
fun updateAppTitle(title: String, packageName: String) fun updateAppTitle(title: String, packageName: String)
@Query("UPDATE home_screen_grid_items SET `left` = :left, `top` = :top, `right` = :right, `bottom` = :bottom WHERE id = :id")
fun updateAppPosition(left: Int, top: Int, right: Int, bottom: Int, id: Long)
@Query("DELETE FROM home_screen_grid_items WHERE package_name = :packageName") @Query("DELETE FROM home_screen_grid_items WHERE package_name = :packageName")
fun deleteItem(packageName: String) fun deleteItem(packageName: String)
} }

View File

@ -10,9 +10,9 @@ import androidx.room.PrimaryKey
data class HomeScreenGridItem( data class HomeScreenGridItem(
@PrimaryKey(autoGenerate = true) var id: Long?, @PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "left") var left: Int, @ColumnInfo(name = "left") var left: Int,
@ColumnInfo(name = "top") val top: Int, @ColumnInfo(name = "top") var top: Int,
@ColumnInfo(name = "right") val right: Int, @ColumnInfo(name = "right") var right: Int,
@ColumnInfo(name = "bottom") val bottom: Int, @ColumnInfo(name = "bottom") var bottom: Int,
@ColumnInfo(name = "package_name") val packageName: String, @ColumnInfo(name = "package_name") val packageName: String,
@ColumnInfo(name = "title") val title: String @ColumnInfo(name = "title") val title: String
) )

View File

@ -69,7 +69,32 @@ class HomeScreenGrid(context: Context, attrs: AttributeSet, defStyle: Int) : Vie
invalidate() invalidate()
} }
// figure out at which cell was the item dropped, if it is empty
fun itemDraggingStopped(x: Int, y: Int) { fun itemDraggingStopped(x: Int, y: Int) {
val center = gridCenters.minBy { Math.abs(it.first - x) + Math.abs(it.second - y) }
// convert stuff like 102x192 to grid cells like 0x1
rowXCoords.forEachIndexed { xIndex, xCell ->
rowYCoords.forEachIndexed { yIndex, yCell ->
if (xCell + rowWidth / 2 == center.first && yCell + rowHeight / 2 == center.second) {
// check if the destination grid item is empty
val targetGridItem = gridItems.firstOrNull { it.left == xIndex && it.top == yIndex }
if (targetGridItem == null) {
gridItems.firstOrNull { it.id == draggedItem?.id }?.apply {
left = xIndex
top = yIndex
right = xIndex + 1
bottom = yIndex + 1
ensureBackgroundThread {
context.homeScreenGridItemsDB.updateAppPosition(left, top, right, bottom, id!!)
}
}
}
}
}
}
draggedItem = null draggedItem = null
invalidate() invalidate()
} }