This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Convert RecycleView to LazyColumn – Jetpack Compose


Step-by-step tutorial to transform Android RecycleView(view-based UI strategy) to LazyColumn (Jetpack Compose strategy)

This text was initially revealed at vtsen.hashnode.dev on Feb 26, 2022.

This beginner-friendly tutorial offers an instance methods to convert this simple RecycleView app to Jetpack Compose.

I additionally take some further steps to wash up unused code or xml after migrating to Jetpack Compose.



1. Take away RecycleView, Structure, Fragment and Library Information

Apart from RecycleView, you can even take away the fragment and structure recordsdata, since Jetpack Compose does not want them.



Take away undesirable supply codes

  • MainFragment.kt
  • RecyceViewAdapter.kt
  • ItemViewHolder.kt
  • ItemDiffCallback.kt



Take away undesirable structure recordsdata

  • main_activity.xml
  • main_fragment.xml
  • merchandise.xml



Take away undesirable construct options and libraries

In appbuild.gradle, take away data binding since that is now not applicableto Jetpack Compose.

buildFeatures {
    dataBinding true
}
Enter fullscreen mode

Exit fullscreen mode

Take away these dependencies as properly.

dependencies {
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    implementation 'androidx.fragment:fragment-ktx:1.4.0'
}
Enter fullscreen mode

Exit fullscreen mode



Repair compilation situation in MainActivity.kt

Take away this code in MainActivity::onCreate() because you now not want fragment.

setContentView(R.structure.main_activity)
if (savedInstanceState == null) {
    supportFragmentManager.beginTransaction()
        .change(R.id.container, MainFragment.newInstance())
        .commitNow()
}
Enter fullscreen mode

Exit fullscreen mode

It is best to be capable of construct efficiently now.



2 Setup Jetpack Compose Libraries



Replace construct.gradle (mission degree)

Add compose_version extension contained in the buildScript{ } in order that the compose model could be referenced later.

buildscript {
    ext {
        compose_version = '1.0.5'
    }
    ...
}
Enter fullscreen mode

Exit fullscreen mode



Replace appbuild.gradle(app degree)

Add compose construct options and kotlinCompilerExtensionVersion compose choices.

android {
    ....
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
    }
    ....
}
Enter fullscreen mode

Exit fullscreen mode

Change implementation 'androidx.appcompat:appcompat:1.4.0' with implementation 'androidx.exercise:activity-compose:1.4.0' and add the next Jetpack Compose dependencies.

dependencies {
    ...
    implementation 'androidx.exercise:activity-compose:1.4.0'
    ...
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.materials:materials:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
    ...
}
Enter fullscreen mode

Exit fullscreen mode



Replace MainActivity for compose

In Jetpack Compose, you do not want AppCompatActivity anymore, you’ll be able to simply immediately inherit from ComponentActivity

Modify MainActivity to immediately inherit from ComponentActivity, overrides onCreate() and name SetContent{} which permit any @composable capabilities could be known as inside.

class MainActivity : ComponentActivity() {
    ...
    override enjoyable onCreate(savedInstanceState: Bundle?) {  
        tremendous.onCreate(savedInstanceState)  
        setContent {
            // Implement composable operate right here.  
        }  
    }
}
Enter fullscreen mode

Exit fullscreen mode



3. Add Theming in Jetpack Compose

Earlier than you add theming in Jetpack Compose, let’s clear up the colours.xml and themes.xml.

You solely require the themes.xml to offer the colour for android:statusBarColor. So you retain it and eradicating the rest.



Clear up colours.xml and themes.xml

These must be the minimal code required to customise the standing bar coloration.

colours.xml

<?xml model="1.0" encoding="utf-8"?>
<sources>
    <coloration title="purple_700">#FF3700B3</coloration>
</sources>
Enter fullscreen mode

Exit fullscreen mode

themes.xml

<sources xmlns:instruments="http://schemas.android.com/instruments">
    <fashion title="Theme.RecycleViewDemo" dad or mum="Theme.MaterialComponents.DayNight.DarkActionBar">
        <merchandise title="colorPrimaryVariant">@coloration/purple_700</merchandise>
        <merchandise title="android:statusBarColor" instruments:targetApi="l">?attr/colorPrimaryVariant</merchandise>
    </fashion>
</sources>
Enter fullscreen mode

Exit fullscreen mode

themes.xml (night time)

<sources xmlns:instruments="http://schemas.android.com/instruments">
    <fashion title="Theme.RecycleViewDemo" dad or mum="Theme.MaterialComponents.DayNight.DarkActionBar">
        <merchandise title="colorPrimaryVariant">@coloration/purple_700</merchandise>
        <merchandise title="android:statusBarColor" instruments:targetApi="l">?attr/colorPrimaryVariant</merchandise>
    </fashion>
</sources>
Enter fullscreen mode

Exit fullscreen mode



Add Compose Theming

Create ui.theme bundle folder, places the Colours.kt, Form.kt, Kind.kt into this folder.

Colours.kt

val Purple200 = Colour(0xFFBB86FC)
val Purple500 = Colour(0xFF6200EE)
val Purple700 = Colour(0xFF3700B3)
val Teal200 = Colour(0xFF03DAC5)
Enter fullscreen mode

Exit fullscreen mode

Form.kt

val Shapes = Shapes(
    small = RoundedCornerShape(4.dp),
    medium = RoundedCornerShape(4.dp),
    giant = RoundedCornerShape(0.dp)
)
Enter fullscreen mode

Exit fullscreen mode

Kind.kt

val Typography = Typography(
    body1 = TextStyle(
        fontFamily = FontFamily.Default,
        fontWeight = FontWeight.Regular,
        fontSize = 16.sp
    )
)
Enter fullscreen mode

Exit fullscreen mode

Theme.kt

non-public val DarkColorPalette = darkColors(
    major = Purple200,
    primaryVariant = Purple700,
    secondary = Teal200
)

non-public val LightColorPalette = lightColors(
    major = Purple500,
    primaryVariant = Purple700,
    secondary = Teal200
)

@Composable
enjoyable RecycleViewDemoTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content material: @Composable() () -> Unit
) {
    val colours = if (darkTheme) {
        DarkColorPalette
    } else {
        LightColorPalette
    }

    MaterialTheme(
        colours = colours,
        typography = Typography,
        shapes = Shapes,
        content material = content material
    )
}
Enter fullscreen mode

Exit fullscreen mode

These recordsdata help you customise your theme for Jetpack Compose.

To theme your app, name the MainContent() composable operate from RecycleViewDemoTheme. The code seems to be like this:

class MainActivity : ComponentActivity() {
    override enjoyable onCreate(savedInstanceState: Bundle?) {
        tremendous.onCreate(savedInstanceState)
        setContent {
            MainScreen()
        }
    }
}

@Composable
enjoyable MainScreen() {
    RecycleViewDemoTheme {
        MainContent()
    }
}

@Composable
enjoyable MainContent() {
    //Todo: Implement LazyColumn
}
Enter fullscreen mode

Exit fullscreen mode



4. Add Prime App Bar

Since you might have eliminated AppCompatActivity, the highest app bar will not be created anymore. You want to create it utilizing Jetpack Compose.



Add Scaffold() composable operate

To create high app bar, you utilize ScaffoldI() composable operate. The code seems to be like this:

@Composable
enjoyable MainScreen() {
    RecycleViewDemoTheme {
        Scaffold(
            topBar = { TopAppBar (title = {Textual content(stringResource(R.string.app_name))})
            }
        ) {
            MainContent()
        }
    }
}
Enter fullscreen mode

Exit fullscreen mode



Preview a composable operate

In an effort to preview a composable operate, you add the next code:

@Preview(showBackground = true)
@Composable
enjoyable DefaultPreview() {
    MainScreen()
}

Enter fullscreen mode

Exit fullscreen mode

After you compile, it is best to see one thing like this at your proper. In the event you run your app, it is best to see the identical UI as in preview.

Convert_RecycleView_to_LazyColumn_02.png

Now the app is totally carried out with Jetpack Compose code. At this level, the UI is precisely similar because the view-based UI strategy with out the recycle view content material.



5. Implement LazyColumn Composable Perform

The equal RecycleView in Jetpack compose is LazyColumn composable operate.

Strictly talking, they don’t seem to be the identical. LazyColumn does not likely recycle the merchandise UI. It simply recreates your entire merchandise UI. So in concept, RecycleView efficiency must be higher than the LazyColumn.

The benefit of LazyColumn it makes use of much less code since RecycleView has a number of boilerplate code. See what number of steps are required to implement RecyceView right here:



Create MainViewModel and move into MainContent

Because the information is coming MainViewModel, you create it with by viewModels delegated property within the MainActivity move it as parameter to the MainContent() composable operate.

MainActivity.kt

class MainActivity : ComponentActivity() {  
    val viewModel by viewModels<MainViewModel>()  

    override enjoyable onCreate(savedInstanceState: Bundle?) {  
        tremendous.onCreate(savedInstanceState)  
        setContent {  
            MainScreen(viewModel)  
        }  
    }  
}
Enter fullscreen mode

Exit fullscreen mode

by viewModels is used in order that you do not recreate the MainViewModel occasion when the MainActivity is destroyed and recreated. See explaination here.

MainScreen.kt

@Composable
enjoyable MainScreen(viewModel: MainViewModel) {
    RecycleViewDemoTheme {
        Scaffold(
            topBar = { TopAppBar (title = {Textual content(stringResource(R.string.app_name))})
            }
        ) {
            MainContent(viewModel)
        }
    }
}
Enter fullscreen mode

Exit fullscreen mode



Convert the LiveData to State

In Jetpack Compose, it’s worthwhile to convert the LiveData<T> to State<T> so it may possibly recompose accurately when the information is modified or up to date. To transform it, you utilize observeAsState() LiveData operate.

Earlier than that, it’s worthwhile to add this library dependency:

implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
Enter fullscreen mode

Exit fullscreen mode

After changing to State<T>, you previous the worth(i.e. Listing<ItemData>) as parameters ofListContent() composable operate.

@Composable
enjoyable MainContent(viewModel: MainViewModel) {
    val itemsState = viewModel.gadgets.observeAsState()

    itemsState.worth?.let { gadgets ->
        ListContent(gadgets)
    }
}
Enter fullscreen mode

Exit fullscreen mode



Implement LazyColumn

Because the RecycleView merchandise unique implementation replenish your entire display width and middle aligned, it’s worthwhile to do the identical. This may be accomplished by means of modifer and horizontalAlignment parameters of LazyColumn

Within the final parameter of LazyColumn is Function Literal (Lambda Function) with Receiver. The LazyListScope is the receiver.

So as to add the gadgets (i.e Listing<ItemData>), you name the LazyListSciope.gadgets() composable operate. So as to add the gadgets content material, you implement the ShowItem() composable operate which simply present the textual content.

To match the unique RecycleView implementation, we set the font dimension to 34.sp and FontWeight.Daring.

The code seems to be like this:

@Composable
enjoyable ListContent(gadgets: Listing<ItemData>) {
    LazyColumn (
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        gadgets(gadgets = gadgets) { merchandise ->
            ShowItem(merchandise)
        }
    }
}

@Composable
enjoyable ShowItem(merchandise: ItemData) {
    Textual content(
        textual content = merchandise.id.toString(),
        fontSize = 34.sp,
        fontWeight = FontWeight.Daring
    )
}
Enter fullscreen mode

Exit fullscreen mode



Replace Preview to incorporate MainViewModel creation

Because the MainScreen() takes in MainViewModel as parameter, it’s worthwhile to create it and move it in.

@Preview(showBackground = true)
@Composable
enjoyable DefaultPreview() {
    val viewModel = MainViewModel()
    MainScreen(viewModel)
}
Enter fullscreen mode

Exit fullscreen mode



6. Completed

It’s lastly accomplished!. The app seems to be like this, which is precisely the identical with the RecycleView view-based UI strategy.

Convert_RecycleView_to_LazyColumn_03.png

In order for you, you can even refactor the code by transferring out the MainContent() composable operate to a seperate file which is a bit cleaner.



Reference



See Additionally

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?