• Stars
    star
    174
  • Rank 219,104 (Top 5 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created 11 months ago
  • Updated 18 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Seamlessly integrate Jetpack Compose composables in RecyclerView with ComposeRecyclerView🔥. This library enhances performance⚡, tackles LazyList issues🔨, and offers built-in drag-and-drop👨🏽‍💻 support for dynamic UIs.

ComposeRecyclerView

ComposeRecyclerView enables seamless integration of Jetpack Compose composables within traditional RecyclerView. This library addresses performance concerns and resolves issues commonly faced in Compose LazyList implementations. It comes with built-in support for drag-and-drop functionality, making it a versatile solution for dynamic UIs.

Blue Pink Gradient Fashion Banner (1)

Benefits

  • Improved Performance: ComposeRecyclerView optimizes the rendering of Jetpack Compose items within a RecyclerView, providing better performance compared to LazyList implementations.

  • Drag-and-Drop Support: Built-in support for drag-and-drop functionality makes it easy to implement interactive and dynamic user interfaces.

  • Flexible Configuration: Customize the layout, item creation, and callbacks to fit your specific UI requirements.

  • Multi-Item Type Support: Easily handle multiple item types within the same RecyclerView, enhancing the versatility of your UI.

How to add in your project

Add the dependency

 implementation 'com.canopas:compose_recyclerview:1.0.2'

Sample Usage

Integrating ComposeRecyclerView into your Android app is a breeze! Follow these simple steps to get started:

Implement ComposeRecyclerView:

Use the ComposeRecyclerView composable to create a RecyclerView with dynamically generated Compose items.

ComposeRecyclerView(
    modifier = Modifier.fillMaxSize(),
    itemCount = yourTotalItemCount,
    itemBuilder = { index ->
        // Compose content for each item at the specified index
        // Similar to Flutter's ListView.builder() widget
        // Customize this block based on your UI requirements
    },
    onScrollEnd = {
        // Callback triggered when the user reaches the end of the list during scrolling
        // Add your logic to handle the end of the list, such as loading more data
    },
    itemTouchHelperConfig = {
        nonDraggableItemTypes = setOf(yourHeaderItemType)
        onMove = { recyclerView, viewHolder, target ->
            // Handle item move
        }
        onSwiped = { viewHolder, direction ->
            // Handle item swipe
        }
        dragDirs = UP or DOWN or START or END // Specify drag directions here
        swipeDirs = LEFT or RIGHT // Specify swipe directions here
        // Add more customization options as needed
    }
)

Customize as Needed:

Customize the layout, handle item types, and add drag-and-drop functionality based on your project requirements.

itemTypeBuilder = object : ComposeRecyclerViewAdapter.ItemTypeBuilder {
    override fun getItemType(position: Int): Int {
        // Determine the item type based on the position
        // Customize this logic based on your requirements
        return yourItemType
    }
}

onItemMove = { fromPosition, toPosition, itemType ->
    // Update your data structure when an item is moved
    // Customize this block based on your data structure
}

onDragCompleted = { position ->
    // Handle item drag completion (e.g., update the UI or perform an API call)
    // Customize this block based on your requirements
}

Customize Layout (Optional):

You can customize the layout of your RecyclerView as needed.

recyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
// OR
recyclerView.layoutManager = GridLayoutManager(context, yourSpanCount)

ComposeRecyclerView in Action: Creating Complex UIs with Drag-and-Drop

Sample.Video.mp4

Sample Implementation

const val ITEM_TYPE_FIRST_HEADER = 0
const val ITEM_TYPE_FIRST_LIST_ITEM = 1
const val ITEM_TYPE_SECOND_HEADER = 2
const val ITEM_TYPE_SECOND_LIST_ITEM = 3

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeRecyclerViewTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    val userDataList = List(20) { index ->
                        UserData(
                            "User ${index + 1}",
                            20 + index,
                            if (index % 2 == 0) "Male" else "Female"
                        )
                    }

                    val otherUsersDataList = List(20) { index ->
                        UserData(
                            "User ${index + 21}",
                            20 + index,
                            if (index % 2 == 0) "Male" else "Female"
                        )
                    }

                    ComposeRecyclerView(
                        modifier = Modifier.fillMaxSize(),
                        itemCount = 1 + userDataList.size + 1 + otherUsersDataList.size,
                        itemBuilder = { index ->
                            if (index == 0) {
                                Box(
                                    modifier = Modifier.fillMaxWidth(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        "First List Header Composable",
                                        style = MaterialTheme.typography.titleMedium,
                                        modifier = Modifier.padding(16.dp)
                                    )
                                }
                                return@ComposeRecyclerView
                            }

                            val userIndex = index - 1
                            if (userIndex < userDataList.size) {
                                CustomUserItem(user = userDataList[userIndex])
                                return@ComposeRecyclerView
                            }

                            if (userIndex == userDataList.size) {
                                Box(
                                    modifier = Modifier.fillMaxWidth(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        "Second List Header Composable",
                                        style = MaterialTheme.typography.titleMedium,
                                        modifier = Modifier.padding(16.dp)
                                    )
                                }
                                return@ComposeRecyclerView
                            }

                            val otherUserIndex = index - userDataList.size - 2
                            if (otherUserIndex < otherUsersDataList.size) {
                                CustomUserItem(user = otherUsersDataList[otherUserIndex])
                                return@ComposeRecyclerView
                            }
                        },
                        onItemMove = { fromPosition, toPosition, itemType ->
                            // Update list when an item is moved
                            when (itemType) {
                                ITEM_TYPE_FIRST_HEADER -> {
                                    // Do nothing
                                }

                                ITEM_TYPE_FIRST_LIST_ITEM -> {
                                    val fromIndex = fromPosition - 1
                                    val toIndex = toPosition - 1
                                    Collections.swap(userDataList, fromIndex, toIndex)
                                }

                                ITEM_TYPE_SECOND_HEADER -> {
                                    // Do nothing
                                }

                                // ITEM_TYPE_SECOND_LIST_ITEM
                                else -> {
                                    val fromIndex = fromPosition - userDataList.size - 2
                                    val toIndex = toPosition - userDataList.size - 2
                                    Collections.swap(otherUsersDataList, fromIndex, toIndex)
                                }
                            }
                        },
                        onDragCompleted = {
                            // Update list or do API call when an item drag operation is completed
                            Log.d("MainActivity", "onDragCompleted: $it")
                        },
                        itemTypeBuilder = object : ComposeRecyclerViewAdapter.ItemTypeBuilder {
                            override fun getItemType(position: Int): Int {
                                // Determine the item type based on the position
                                // You can customize this logic based on your requirements
                                return when {
                                    position == 0 -> ITEM_TYPE_FIRST_HEADER // Header type
                                    position <= userDataList.size -> ITEM_TYPE_FIRST_LIST_ITEM // First list item type
                                    position == userDataList.size + 1 -> ITEM_TYPE_SECOND_HEADER // Header type
                                    else -> ITEM_TYPE_SECOND_LIST_ITEM // Second list item type
                                }
                            }
                        },
                        onScrollEnd = {
                            // Do API call when the user reaches the end of the list during scrolling
                            Log.d("MainActivity", "onScrollEnd")
                        },
                        itemTouchHelperConfig = {
                            nonDraggableItemTypes =
                                setOf(ITEM_TYPE_FIRST_HEADER, ITEM_TYPE_SECOND_HEADER)

                            /*onMove = { recyclerView, viewHolder, target ->
                                // Handle item move
                            }
                            onSwiped = { viewHolder, direction ->
                                // Handle item swipe
                            }
                            // Add more customization options as needed*/
                        },
                    ) { recyclerView ->
                        recyclerView.addItemDecoration(
                            DividerItemDecoration(
                                recyclerView.context,
                                DividerItemDecoration.VERTICAL
                            )
                        )

                        // To change layout to grid layout
                        val gridLayoutManager = GridLayoutManager(this, 2).apply {
                            spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                                override fun getSpanSize(position: Int): Int {
                                    return if (position == 0 || position == userDataList.size + 1) {
                                        2 // To show header title at the center of the screen and span across the entire screen
                                    } else {
                                        1
                                    }
                                }
                            }
                        }
                        recyclerView.layoutManager = gridLayoutManager
                    }
                }
            }
        }
    }
}

@Composable
fun CustomUserItem(user: UserData) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.Black,
            contentColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 8.dp
        ),
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier
                .padding(16.dp)
        ) {
            Text(
                text = "Name: ${user.name}",
                style = MaterialTheme.typography.titleMedium,
                color = Color.White
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "Age: ${user.age}",
                style = MaterialTheme.typography.titleMedium,
                color = Color.White
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "Gender: ${user.gender}",
                style = MaterialTheme.typography.titleMedium,
                color = Color.White
            )
        }
    }
}

Linear Layout

Grid Layout

Demo

To see ComposeRecyclerView in action, check out our Sample app.

Bugs and Feedback

For bugs, questions and discussions please use the Github Issues

Credits

ComposeRecyclerView is owned and maintained by the Canopas team. For project updates and releases, you can follow them on Twitter at @canopassoftware.

Acknowledgments

Jetpack Compose Interop Article: We express our appreciation to the Jetpack Compose Interop Article on Medium by Chris Arriola. This article provided valuable insights and guidance on supporting Jetpack Compose in RecyclerView, helping us understand the intricacies of integration and contributing to the realization of our own ideas.

Licence

Copyright 2023 Canopas Software LLP

Licensed under the Apache License, Version 2.0 (the "License");
You won't be using 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.

More Repositories

1

compose-intro-showcase

Highlight different features of the app using Jetpack Compose
Kotlin
478
star
2

compose-animations-examples

Cool animations implemented with Jetpack compose
Kotlin
376
star
3

UIPilot

The missing typesafe SwiftUI navigation library
Swift
307
star
4

compose-animated-navigationbar

Cool animated navigation bars for your compose android app.
Kotlin
156
star
5

tailwind-animations-examples

Cool animations implemented with tailwindcss
Vue
117
star
6

web-developer-roadmap

Web Developer Roadmap is a path to understand web development including frontend, backend and cloud.
106
star
7

iOS-developer-roadmap

iOS Developer Roadmap 2022 is a learning path to understand iOS development.
93
star
8

animated_reorderable_list

A Flutter Reorderable Animated List with simple implementation and smooth transition.
Dart
79
star
9

rich-editor-swiftui

RichEditorSwiftUI is swift based library, it is made to make rich text editing easy with SwiftUI.
Swift
73
star
10

rich-editor-compose

Android WYSIWYG Rich editor for Jetpack compose.
Kotlin
72
star
11

swiftui-animations-examples

Cool animations implemented with SwiftUI
Swift
69
star
12

android-developer-roadmap-2023

The Android Developer Roadmap 2023 includes 29 practical exercises that cover all the essential concepts used in day-to-day development.
68
star
13

group-track-flutter

Dart
66
star
14

compose-country-picker

Country code bottomsheet picker in Jetpack Compose
Kotlin
59
star
15

group-track-android

An open-source Android app employing MVVM architecture and Jetpack Compose. Enhance family safety with real-time location sharing.
Kotlin
56
star
16

canopas-blog-admin

Feature-Rich blogs admin panel built with strapi CMS
JavaScript
46
star
17

splito

An open-source iOS app employing MVVM architecture and SwiftUI. Simplifying group expense management is easy and fair among friends and family.
Swift
35
star
18

canopas-website

Responsive website built with Vue.js and vite by following best practices.
Vue
33
star
19

khelo

Khelo - An open-source app for easy cricket team management and performance tracking.
Dart
33
star
20

iOS-developer-roadmap-2023

The iOS Developer Roadmap 2023 includes 29 practical exercises that cover all the essential concepts used in day-to-day development.
32
star
21

nuxt-blog-kit

Nuxt Blog Kit is Component library built with Nuxt3 and Tailwind.
Vue
31
star
22

vue-file-upload

A file management system built with Vue.js and TypeScript that allows for single and multiple file uploading with a preview feature
Vue
31
star
23

gorm-gin-with-mysql

Golang : Use gorm with mysql in gin
Go
30
star
24

strapi-plugin-tagsinput

Tagsinput plugin for strapi
JavaScript
28
star
25

animated-visibility

Animate appearance and disappearance using pre-built effects with the AnimatedVisibility widget.
Dart
28
star
26

web-developer-roadmap-2023

Web Developer Roadmap 2023 is a path to understand web development including frontend, backend and cloud.
27
star
27

flutter-country-picker

A Simple, Customizable Flutter Country picker for picking a Country or Dialing code with Search functionality.
Dart
21
star
28

canopas_unity

Unity - A multiplatform leave management app built in Flutter framework using Firestore database and storage
Dart
20
star
29

web-file-upload

A file management system built for vue and react that allows for single and multiple file uploading with a preview feature.
TypeScript
20
star
30

flutter-developer-roadmap-2023

19
star
31

fullstack-graphql-react-starter-kit

A boilerplate project for building web applications using the Apollo GraphQL, Typescript, Express.js, Vite and React.js
TypeScript
15
star
32

cloud-gallery

Enjoy all your media in one spot! Easily view and manage photos, videos from Google Drive, Dropbox, and your device, all in a simple, user-friendly interface.
Dart
13
star
33

Android-developer-roadmap

Android developer roadmap 2022 is a path to start your journey with android development.
11
star
34

MarqueeScroll

Marquee scroll with infinite scrolling and auto direction detect(Demo)
Swift
10
star
35

bite-space

A food web app for food lovers which is built in nextjs to discover popular foods and restaurants/cafes near you or where you want.
TypeScript
8
star
36

serverless-php-example

AWS lambda function with Laravel and Codeigniter -- serverless example
PHP
6
star
37

android-devOps-roadmap

6
star
38

web-devops-roadmap

A comprehensive guide for web developers to master DevOps practices in their workflow.
5
star
39

go-reusable-functions

Reusable functions in golang.
Go
4
star
40

GinMiddleware

Middleware implemented in golang using gin framework
Go
4
star
41

react-file-upload

A file management system built with React, Next,js and TypeScript that allows for single and multiple file uploading with a preview feature
TypeScript
4
star
42

go-rss-feeds

RSS feeds example in golang
Go
3
star
43

Ytech-mvvm-jetpack-compose

Kotlin
3
star
44

apple-sdk-go

Apple client services build with go
Go
3
star
45

flutter-developer-roadmap

Roff
3
star
46

yTech-screenshot-testing-compose

Kotlin
2
star
47

electron-twitter-login-example

Electron-vue Twitter login example app
JavaScript
2
star
48

ios-todo-app-with-unit-testing

Sample code for the articles written on Ultimate guide to iOS unit testing. https://blog.canopas.com/the-ultimate-guide-to-ios-unit-testing-with-best-practices-part-1-c3a484b8dc8d
Swift
1
star
49

iOS-DevOps-Roadmap

A comprehensive guide for iOS developers to master DevOps practices in their workflow.
1
star
50

TGProgress

Swift
1
star
51

docker-php-fpm

Dockerfile
1
star
52

json-to-struct-converter

Go
1
star