Open In App

Horizontal ListView in Android using Jetpack Compose

Last Updated : 08 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Many Android Applications present data in the form of horizontally scrollable lists. This list can be scrolled horizontally. In this article, we will take a look at How to Implement Horizontal ListView in Android Applications using Jetpack Compose. 

Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only available in Kotlin. It uses features such as coroutines, and the handling of @Composable annotations is handled by a Kotlin compiler. There is no method for Java to access these. Therefore, you cannot use Jetpack Compose if your project does not support Kotlin.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Creating a Model Class

Navigate to the app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and name your class as ListModel and add the below code to it. Comments are added to the code for further explanation. 

Kotlin




// in the below line, we are creating a
// model class for our data class.
data class ListModel(
     
    // in the below line, we are creating two variable
    // one is for language name which is string.
    val languageName: String,
     
    // next variable is for our
    // image which is an integer.
    val languageImg: Int
)


Step 3: Adding a New Color in the Color.kt File

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. Comments are added in the code for further explanation. 

Kotlin




import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// in the below line, we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 4: Adding Images to the Drawable Folder

Copy all the images which you want to add to your grid view. Navigate to app > res > drawable. Right-click on it and paste all the images into the drawable folder.

Step 5: Working with the MainActivity.kt File

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added to the code for further explanation. 

Kotlin




import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import coil.compose.rememberAsyncImagePainter
import com.example.newcanaryproject.ui.theme.*
import java.util.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // in the below line, we are specifying
                // background color for our application
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    // in the below line, we are specifying theme as scaffold.
                    Scaffold(
                        // in scaffold we are specifying top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying title for our top bar.
                                title = {
                                    // in the top bar we are specifying title as a text
                                    Text(
                                        // in the below line, we are specifying text
                                        // to display in top app bar.
                                        text = "Horizontal List View Example",
 
                                        // in the below line, we are specifying modifier
                                        // to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // in the below line, we are specifying text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // in the below line, we are specifying color for our text.
                                        color = Color.White
                                    )
                                }
                            )
                        }
                    ) {
                        // in the below line, we are calling custom list
                        // view function to display custom listview.
                        customListView(LocalContext.current)
                    }
                }
            }
        }
    }
}
 
 
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun customListView(context: Context) {
    // in the below line, we are creating and
    // initializing our array list
    lateinit var courseList: List<ListModel>
    courseList = ArrayList<ListModel>()
 
    // in the below line, we are adding data to our list.
    courseList = courseList + ListModel("Android", R.drawable.android)
    courseList = courseList + ListModel("JavaScript", R.drawable.js)
    courseList = courseList + ListModel("Python", R.drawable.python)
    courseList = courseList + ListModel("C++", R.drawable.c)
    courseList = courseList + ListModel("C#", R.drawable.csharp)
    courseList = courseList + ListModel("Java", R.drawable.java)
    courseList = courseList + ListModel("Node Js", R.drawable.nodejs)
 
    // in the below line, we are creating a
    // lazy row for displaying a horizontal list view.
    LazyRow {
        // in the below line, we are setting data for each item of our listview.
        itemsIndexed(courseList) { index, item ->
            // in the below line, we are creating a card for our list view item.
            Card(
                // inside our grid view on below line
                // we are adding on click for each item of our grid view.
                onClick = {
                    // inside on click we are displaying the toast message.
                    Toast.makeText(
                        context,
                        courseList[index].languageName + " selected..",
                        Toast.LENGTH_SHORT
                    ).show()
                },
                // in the below line, we are adding
                // padding from our all sides.
                modifier = Modifier
                    .padding(8.dp)
                    .width(120.dp),
 
                // in the below line, we are adding
                // elevation for the card.
                elevation = 6.dp
            )
            {
                // in the below line, we are creating
                // a row for our list view item.
                Column(
                    // for our row we are adding modifier
                    // to set padding from all sides.
                    modifier = Modifier
                        .padding(8.dp)
                        .fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // in the below line, inside row we are adding spacer
                    Spacer(modifier = Modifier.height(5.dp))
 
                    // in the below line, we are adding Image to display the image.
                    Image(
                        // in the below line, we are specifying the drawable image for our image.
                        painter = painterResource(id = courseList[index].languageImg),
 
                        // in the below line, we are specifying
                        // content description for our image
                        contentDescription = "img",
 
                        // in the below line, we are setting height
                        // and width for our image.
                        modifier = Modifier
                            .height(60.dp)
                            .width(60.dp)
                            .padding(5.dp),
 
                        alignment = Alignment.Center
                    )
 
                    // in the below line, we are adding spacer between image and a text
                    Spacer(modifier = Modifier.height(5.dp))
 
                    // in the below line, we are creating a text.
                    Text(
                        // inside the text on below line we are
                        // setting text as the language name
                        // from our model class.
                        text = courseList[index].languageName,
 
                        // in the below line, we are adding padding
                        // for our text from all sides.
                        modifier = Modifier.padding(4.dp),
 
                        // in the below line, we are adding color for our text
                        color = Color.Black, textAlign = TextAlign.Center
                    )
                }
            }
        }
    }
}


Now run your application to see the output of it.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads