• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

How to Migrate File Drag Source from Jetpack Compose 1.7.3 to 1.8.0?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Introduction


If you've recently upgraded Jetpack Compose from version 1.7.3 to 1.8.0, you might be facing issues with the dragging functionality. The startTransfer() method, which worked seamlessly in previous versions, has become deprecated in version 1.8.0, leading to the frustrating 'Unresolved reference' error. This article will guide you through the migration process and provide you with functional code that aligns with the new API specifications.

Why the Issue Occurs


In Jetpack Compose 1.8.0, significant changes were made to the drag-and-drop API, including the removal of the startTransfer() method. Such enhancements often aim to improve performance and usability but can be challenging for developers when updating code from earlier versions. Migrating to the new API requires understanding the new methods introduced for drag-and-drop functionality.

Updating the Drag Source function


To migrate your fileDragSource function effectively, we’ll implement the new API changes that Jetpack Compose 1.8.0 introduces. Here’s a step-by-step solution to help you port your existing functionality.

Step 1: Replace startTransfer with the new API


The new API in Jetpack Compose requires a different approach to initiate a drag and drop action. The previous startTransfer() method will be replaced with setDragData() and then invoking the drag action itself using dragAndDropSource().

Step 2: Adjust the drag gesture detection


You'll still need to use the detectDragGestures method, but the parameters and handling will be adjusted to fit the new architecture.

Code Example


Below is the adapted code that adheres to the changes of Jetpack Compose 1.8.0:

@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
fun Modifier.fileDragSource(
path: Path,
onTransferCompleted: ((userAction: DragAndDropTransferAction?) -> Unit)? = null,
drawDragDecoration: (DrawScope.() -> Unit)? = debugDrawDragDecoration()
): Modifier = dragAndDropSource(
drawDragDecoration = {
drawDragDecoration?.invoke(this)
},
) {
detectDragGestures(
onDragStart = { offset ->
// Create the new transferable data
val data = DragAndDropTransferData(
DragAndDropTransferable(
PathTransferable(path)
),
supportedActions = listOf(
DragAndDropTransferAction.Copy,
DragAndDropTransferAction.Move,
DragAndDropTransferAction.Link,
)
)

// Set the drag data with the new API
setDragData(data)

onTransferCompleted?.invoke(null) // Invoke completion with no action initially
},
onDrag = { change, dragAmount ->
// Handle dragging content
},
onDragEnd = { onTransferCompleted?.invoke(DragAndDropTransferAction.Move) },
onDragCancel = { onTransferCompleted?.invoke(null) } // Notify about drag cancellation
)
}

Explanation of Changes

  • The function signature remains similar. However, the crucial difference lies in handling the drag action specifically by using setDragData() to initiate the drag within the onDragStart callback.
  • The onDragEnd and onDragCancel callbacks allow you to handle the completion of the drag, notifying you whether it continues successfully or is canceled.
Frequently Asked Questions (FAQ)

What is the DebugDrawDragDecoration()?


The debugDrawDragDecoration() function is a placeholder in your drag source function, which can be defined to customize the visual feedback during the drag operation. You can implement it based on your requirements.

Is there official migration documentation?


At the moment, specific migration guides might not be available from Jetpack Compose, but the official

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

provides valuable insights into the new drag-and-drop capabilities.

How can I test the drag-and-drop functionality?


Testing the drag-and-drop functionality can be done using Emulator or physical devices, ensuring that you test the interactions properly to confirm that the file moving and dragging actions are registered correctly in your app.

Conclusion


Migrating your drag source from Jetpack Compose 1.7.3 to 1.8.0 may seem daunting at first due to breaking changes, but by replacing the deprecated methods and updating your drag gesture detection logic, you can adapt your code smoothly. This guide has presented a clear path to accomplish this, enhancing your app's functionality with the latest versions of Jetpack Compose.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу