Android JetPack Compose simple list with clickable item
Here is an example of creating a simple list with clickable items with Jetpack Compose.
GreetingList is the custom composable for showing a list of items. This is the top container for the list, it uses LazyColumn and items for creating the list. Inside each item, it is calling the GreetingView to actually render the item view. It passes a callback function for the onClick event, when it’s clicked, it just shows a Toast message.
GreetingView is the custom composable for showing the list item view, in this case, it’s just showing a text message. It is composed of Card, Row and a Text. A clickable modifier is added to the Card to receive click event, when a click event is received, it passes the event back up to the caller GreetingList.
GreetingListPreview is just a composable function annotated with @Preivew to show a preview in Android Studio for this GreetingList composable.
import androidx.compose.foundation.clickable import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme { GreetingList() } } } } @Composable private fun GreetingList(greetings: List= List(100){"$it"}) { val context = LocalContext.current LazyColumn(modifier = Modifier.padding(vertical = 4.dp)) { items(items = greetings) { name -> GreetingView(name = name) { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } } } } @Composable private fun GreetingView(name: String, onClick: (msg: String) -> Unit) { val msg = "Hello, $name" Card( backgroundColor = MaterialTheme.colors.primary, modifier = Modifier .padding(vertical = 4.dp, horizontal = 8.dp) .clickable { onClick(msg) } ) { Row(modifier = Modifier.padding(12.dp).fillMaxWidth()) { Text(text = msg) } } } @Preview(showBackground = true, widthDp = 320, heightDp = 320) @Composable fun GreetingListPreview() { MaterialTheme { GreetingList() } }
Search within Codexpedia
Search the entire web