Puck - Make composables draggable with kotlin

Related tags

Jetpack Compose puck
Overview

Puck


Make Composables Draggable.


Including in your project

Gradle

Add below codes to your root build.gradle file (not your module build.gradle file).

allprojects {
    repositories {
        mavenCentral()
    }
}

And add a dependency code to your module's build.gradle file.

dependencies {
    implementation 'com.github.Shivamdhuria:puck:Version'
}

Usage

//Currently just copy the library module to your project. haven't uploaded on jitpack yet

        setContent {
            // this keeps parents size
            val parentSize = remember { mutableStateOf(Size.Zero) } 
            PuckTheme {
                // A surface container using the 'background' color from the theme
                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
                    Box(modifier = Modifier
                        .onGloballyPositioned { coordinates ->
                            //Set parents Size
                            parentSize.value = coordinates.size.toSize()
                        }
                        .fillMaxSize()
                    ) {
                        //Adding puck to Card Composable
                        Card(
                            modifier = Modifier
                                .puck(parentSize, behaviour = FreeForm), backgroundColor = PINK200
                        ) {
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Image(
                                    painterResource(drawable.zoid),
                                    contentDescription = "",
                                    contentScale = ContentScale.Crop,
                                    modifier = Modifier
                                        .height(70.dp)
                                        .width(70.dp)
                                )
                                Text(text = "Card Composable", fontSize = 24.sp, modifier = Modifier.padding(10.dp))
                            }
                        }
                        //Adding puck to Button Composable
                        Button(onClick = { }, modifier = Modifier.puck(parentSize, behaviour = FreeForm, animationDuration = 700)) {
                            Text(text = "Button Composable", fontSize = 24.sp)
                        }
                        
                       //Adding puck to FAB Composable
                        FloatingActionButton(
                            onClick = {},
                            modifier = Modifier
                                .puck(parentSize, FreeForm, animationDuration = 700)
                                .width(90.dp)
                                .height(90.dp),
                        ) {
                            Image(
                                painterResource(drawable.pencil),
                                contentDescription = "",
                                modifier = Modifier
                                    .height(50.dp)
                                    .width(50.dp)
                            )
                        }
                    }
                }
            }

Behaviours

Currently Puck supports three behaviours

  • Freeform
  • Sticky
  • Gravity

FreeForm

Freeform makes Composable draggable anywhere in the screen. If the user drags a composable out of screen area, it is coerced within the bounds of the screen.

For adding Freeform behaviour to any composable, do -

FloatingActionButton(onClick = {},
                            modifier = Modifier
                                .puck(parentSize, behaviour = FreeForm)
                                .width(90.dp)
                                .height(90.dp)) {
                            //Image or anything
                        }

Sticky

You can also make Composables stick to the edges or corners of the screen. Simple flick the Composable in the direction you want it to stick and it will follow the trajectory and stick there. To use stick you need to pass a parameter (EDGES, CORNERS,VERTICAL EDGsE HORIZONATL EDGES). Puck will automatically make the set parameter "sticky".

FloatingActionButton(onClick = {},
                           modifier = Modifier
                                .puck(parentSize, behaviour = Sticky(Corners), animationDuration = 500)
                                .width(90.dp)
                                .height(90.dp),
                            backgroundColor = WHITE200
                        ) {
                            Image()
                        }

Gravity

We can define gravity points with center and radius. Any composable that falls within this circle's gravity field will "zap" towards this center. Note: The circle isn't actualy drawn as above while using puck. I have shown the circle only for demonstration purposes.

val circle = Circle(800f, 1800f, 500f)
FloatingActionButton(onClick = {},
                           modifier = Modifier
                                .puck(parentSize,behaviour = Gravity(circle), animationDuration = 500)
                                .width(90.dp)
                                .height(90.dp),
                            backgroundColor = WHITE200
                        ) {
                            Image()
                        }

Attributes

  • isPointsTowardsCenter - Currently this only works for Sticky(Edges) mode. Composable will always point towards center by using rotation animation. When a composable is dragged, the rotation value is set to default (0f), after the drag ends and the commposable sticks to any of the edges, the composable rotates according and points towards center.

  • animationDuration - This is time taken in milli seconds for the drag animation. The lesser the time the quicker the animation. (Note: When the behaviour is set to Freeform, a composable is draggable without any animation.)

  • focusedSizeMultiplier - When a composable is in pressed state, its size increases by this factor. You can set it to 1, if you don't want to increase it's size when in pressed date

  • onOffsetChanged - This returns the latest int offset of the composable's position after the drag ends. You should ideally use it to save the latest offset in shared preferences/ datastore to use it again and position the composable when the app restarts again.

Code & Issues

If you are a developer and you wish to contribute to the app please raise an issue, discuss, fork and submit a pull request. Follow Github Flow for collaboration!

Find this repository useful? ❤️

Support it by joining starring this repository.
And follow me on Medium, Github and Twitter

Project Maintainers

This project is founded and actively maintained by Shivam Dhuria.

License

Copyright 2021 Shivam Dhuria

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
Aliucord Manager - Aliucord Installer rewrite in Kotlin and Jetpack Compose

Aliucord Manager Aliucord Manager - Aliucord Installer rewrite in Kotlin and Jetpack Compose. INFO: This app is not functional yet, if you want to ins

A particle view library written in kotlin, easy to use
A particle view library written in kotlin, easy to use

particle 中文介绍 This is a handy android library for particle effect. To start with, you need to add it in your root build.gradle at the end of repositor

An implementation of the Bloc pattern for Kotlin and Jetpack Compose

Kotlin Bloc An implementation of the Bloc pattern for Kotlin and Jetpack Compose. Documentation Documentation is available here: https://ptrbrynt.gith

GraphQL based Jetpack Compose and SwiftUI Kotlin Multiplatform project
GraphQL based Jetpack Compose and SwiftUI Kotlin Multiplatform project

MortyComposeKMM Kotlin Multiplatform sample that demonstrates use of GraphQL + Jetpack Compose and SwiftUI

A Kotlin library to use Jetpack Compose in Android and iOS. Allow to write UI for both in Kotin. Still experimental as many compose features are not yet available.
A Kotlin library to use Jetpack Compose in Android and iOS. Allow to write UI for both in Kotin. Still experimental as many compose features are not yet available.

Multiplatform Compose A Kotlin library to use Jetpack Compose in Android and iOS. Allow to write UI for both in Kotin. Still experimental as many comp

A Weather Mobile or Android Native App, in Kotlin built  to see the current weather of suggested countries of Europe and in my current position. In this case, Maputo/Mozambique #WitChallenge #Asked #Option1
A Weather Mobile or Android Native App, in Kotlin built to see the current weather of suggested countries of Europe and in my current position. In this case, Maputo/Mozambique #WitChallenge #Asked #Option1

Witweather_android This is a challenge assigned by Wit, which aimed to build an Android App to visualize the temperature in my current location, in th

Building a Simple Photo App with Jetpack Compose, CameraX, and Kotlin coroutines

Building a Simple Photo App with Jetpack Compose, CameraX, and Kotlin coroutines This repository holds code created as part of the aforementioned tuto

Kotlin, MVVM, Navigation Component, Hilt, Jetpack Compose, Retrofit2

What is this project? This course will replace my old java mvvm introduction: https://codingwithmitch.com/courses/rest-api-mvvm-retrofit2/. Watch the

Morph is an Android library, written in Kotlin, built to work together with Jetpack Compose.
Morph is an Android library, written in Kotlin, built to work together with Jetpack Compose.

Morph Morph is an Android library, written in Kotlin, built to work together with Jetpack Compose. It allows you to transition any view to another vie

Releases(0.0.3)
Owner
Shivam Dhuria
I like building stuff
Shivam Dhuria
ComposePrefs3 is a fully featured library of preference composables for Jetpack Compose.

ComposePrefs3 This is the M3 version of ComposePrefs. The M2 version can be found here. ComposePrefs3 is a preferences library for Jetpack Compose whi

Jamal Mulla 21 Dec 2, 2022
Sample project to demonstrate how to have clear and better interactions between composables and viewmodels.

Form Validation Sample project to demonstrate how to have clear and better interactions between composables and viewmodels. Concepts used uiState conc

Saurabh Pant 20 Dec 22, 2022
🚀🌆🏙 Display differences or animate progress between 2 images or Composables with overlay and customization options, zoom, pan gestures, and progress to observe properties for animating before-after progress

Compose Before-After Composables to display Images, or Composables as before and after composables to display differences or animate progress between

Smart Tool Factory 56 Dec 22, 2022
This library will make it easier to pass arguments between screens in Jetpack Compose.

Compose Navigation This library will make it easier to pass arguments between screens in Jetpack Compose Setup allprojects { repositories { ...

Nguyen Van Tan 1 Oct 30, 2021
Android Jetpack is a set of components, tools and guidance to make great Android apps.

Android Jetpack is a set of components, tools and guidance to make great Android apps. They bring together the existing Support Library and Architecture Components and arrange them into four categories.

Atik Faysal 0 Dec 8, 2021
Make your device sip only small amounts of battery when not in use.

trickle Make your device sip only small amounts of battery when not in use. What Automatically place your device into battery-saver mode when the scre

pyamsoft 3 Dec 21, 2022
Fast android task that finished in only 3 hours, it gets the information from national number without database. I just wanna refine my skills in android basics so I try to make this simple project.

RaqmQawmy it is a fast android task that finished in only 3 hours, it gets the information from national number without database. I just wanna refine

Mahmoud Abdelazim 3 May 15, 2022
神奇宝贝 (PokemonGo) 基于 Jetpack + MVVM + Repository + Paging3 + Kotlin Flow 的实战项目

这是一个小型的 App 项目,涉及到技术:Paging3(network + db),Dagger-Hilt,App Startup,DataBinding,Room,Motionlayout,Kotlin Flow,Coil,JProgressView 等等。

Jack  Deng 1.5k Jan 7, 2023
A simple Snake application to demonstrate the use of Compose for Desktop platform with Kotlin

Snake App using Compose for Desktop A simple Snake desktop application to demonstrate the use of Compose UI toolkit for Desktop platform with Kotlin.

Serge Nino Martin Villasica 12 Nov 18, 2022
Here you can try out Kotlin Multiplatform and Jetpack Compose with some other cutting-edge technologies.

wire The Wire is a Kotlin Multiplatform sample project, currently supporting Android and Windows. Tools And Technolagies Architecture: MVVM MultiThrea

Ali Rezaiyan 9 Aug 16, 2022