So these are my Project Versions:
val compose_version by extra("1.0.0-beta07")
val kotlin_version by extra("1.4.32")
val hilt_version by extra("2.36")
So I have a LazyColum which displays a custom composable card list:
package com.veloce.montageservice.ui.composables
// Here are imports but its too much code for stackoverflow
#Composable
fun SimpleCard(
imageVector: ImageVector,
title: String,
description: String,
#DrawableRes trailingButton: Int? = null,
clickable: () -> Unit
) {
Card(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
.clickable {
clickable()
},
border = BorderStroke(
(0.5).dp,
brush = Brush.horizontalGradient(
colors = listOf(
MaterialTheme.colors.primary, MaterialTheme.colors.primaryVariant
)
)
),
elevation = 5.dp
// backgroundColor = Color.Gray
) {
Row(
modifier = Modifier.padding(8.dp),
horizontalArrangement = if (trailingButton != null) Arrangement.SpaceEvenly else Arrangement.Start
) {
Surface(
shape = CircleShape,
modifier = Modifier.size(50.dp),
color = MaterialTheme.colors.primaryVariant
) {
Icon(
modifier = Modifier.padding(4.dp),
imageVector = imageVector,
contentDescription = "Icon of a building",
tint = Color.White
)
}
Column(
modifier = Modifier.padding(8.dp),
verticalArrangement = Arrangement.SpaceEvenly
) {
Text(
title,
fontWeight = FontWeight.Bold
)
Text(description)
}
trailingButton?.let {
Surface(
shape = CircleShape,
modifier = Modifier.size(35.dp),
color = MaterialTheme.colors.primaryVariant
) {
Icon(
modifier = Modifier.padding(4.dp),
imageVector = ImageVector.vectorResource(id = it),
contentDescription = "Icon of a building",
tint = Color.White
)
}
}
}
}
}
And this should be clickable. It was, but now it's not anymore and I didn't have changed anything in this composable.
Has anyone an idea what went wrong? The scroll function of LazyColumnworks perfectly fine, it's just that I can't click it anymore from one day to the other.
In compose 1.0.0-beta08 there was a breaking API Change (https://developer.android.com/jetpack/androidx/releases/compose-material) which causes the clickable modifier to be ignored. You have to use the onClickparameter of Card instead:
Card(onClick = { count++ }) {
Text("Clickable card content with count: $count")
}
Related
I want to align two texts to be centered vertically to the start of the TaskCard. It works as intended if there are two texts present. However, if there is only one and the other one is null the null one will completely disappear, but will still leave a blank space in its place. How do I get rid of it so I can properly align the text?
#Composable
fun TaskCard(
modifier: Modifier = Modifier,
task: Task,
viewModel: TaskListViewModel = hiltViewModel()
) {
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant
), modifier = modifier.padding()
) {
Surface(
color = MaterialTheme.colorScheme.surfaceVariant, modifier = modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically, modifier = modifier.padding(12.dp)
) {
Column(
modifier = modifier
.weight(1f)
.padding(12.dp)
) {
task.categoryName?.let {
Text(
text = it,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary
)
}
Text(
text = task.taskName,
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onBackground,
)
}
IconButton(
onClick = { viewModel.onEvent(TaskListEvent.OnEditTask(task)) },
modifier = modifier.size(36.dp)
) {
Icon(
imageVector = Icons.Rounded.Edit,
contentDescription = "Edit",
modifier = modifier.padding(horizontal = 2.dp),
tint = MaterialTheme.colorScheme.onBackground
)
}
IconButton(
onClick = { }, modifier = modifier.size(36.dp)
) {
Icon(
imageVector = Icons.Rounded.Notifications,
contentDescription = "Notifications",
modifier = modifier.padding(horizontal = 2.dp),
tint = MaterialTheme.colorScheme.onBackground
)
}
}
}
}
}
As Gabriele Mariotti suggested I've changed the condition under which the code is executed.
from:
task.categoryName?.let
to:
if (!task.categoryName.isNullOrEmpty())
I wanna have this layout in Jetpack Compose. How can I place the image at the bottom of the card and have it a bit outside the card borders? Also how to make sure that the content above won't collide with the image, because the content above can be longer. Thanks very much.
A simple way is to use a Box and apply an Offset to the Image
Box() {
val overlayBoxHeight = 40.dp
Card(
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
) {
//...
}
Image(
painterResource(id = R.drawable.xxxx),
contentDescription = "",
modifier = Modifier
.align(BottomCenter)
.offset(x = 0.dp, y = overlayBoxHeight )
)
}
If you want to calculate the offset you can use a Layout composable.
Something like:
Layout( content = {
Card(
elevation = 10.dp,
modifier = Modifier
.layoutId("card")
.fillMaxWidth()
.height(300.dp)
) {
//...
}
Image(
painterResource(id = R.drawable.conero),
contentDescription = "",
modifier = Modifier
.layoutId("image")
)
}){ measurables, incomingConstraints ->
val constraints = incomingConstraints.copy(minWidth = 0, minHeight = 0)
val cardPlaceable =
measurables.find { it.layoutId == "card" }?.measure(constraints)
val imagePlaceable =
measurables.find { it.layoutId == "image" }?.measure(constraints)
//align the icon on the top/end edge
layout(width = widthOrZero(cardPlaceable),
height = heightOrZero(cardPlaceable)+ heightOrZero(imagePlaceable)/2){
cardPlaceable?.placeRelative(0, 0)
imagePlaceable?.placeRelative(widthOrZero(cardPlaceable)/2 - widthOrZero(imagePlaceable)/2,
heightOrZero(cardPlaceable) - heightOrZero(imagePlaceable)/2)
}
}
You can use Card for main view layout.
To have an icon placed like this, you need to place it with Card into a box, apply Alignment.BottomCenter alignment to image and add paddings.
To make image be under your text, I've added Spacer with size calculated on image size.
#Composable
fun TestView() {
CompositionLocalProvider(
LocalContentColor provides Color.White
) {
Column {
LazyRow {
items(10) {
Item()
}
}
Box(Modifier.fillMaxWidth().background(Color.DarkGray)) {
Text("next view")
}
}
}
}
#Composable
fun Item() {
Box(
Modifier
.padding(10.dp)
) {
val imagePainter = painterResource(id = R.drawable.test2)
val imageOffset = 20.dp
Card(
shape = RoundedCornerShape(0.dp),
backgroundColor = Color.DarkGray,
modifier = Modifier
.padding(bottom = imageOffset)
.width(200.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(20.dp)
) {
Text(
"Title",
modifier = Modifier.align(Alignment.Start)
)
Spacer(modifier = Modifier.size(15.dp))
Text("PM2.5")
Text(
"10",
fontSize = 35.sp,
)
Text("m/s")
Spacer(modifier = Modifier.size(15.dp))
Text(
"Very Good",
fontSize = 25.sp,
)
Spacer(
modifier = Modifier
.size(
with(LocalDensity.current) { imagePainter.intrinsicSize.height.toDp() - imageOffset }
)
)
}
}
Image(
painter = imagePainter,
contentDescription = "",
Modifier
.align(Alignment.BottomCenter)
)
}
}
Result:
I got into Jetpack compose and I am having a hard time finding examples of a normal screen. Everyone just uses scaffold and calls it a day. Using fillMaxSize is supposed to do exactly this, can someone explain how composable inherit their size? The topmost composable specifically (root composable)?
#Composable
fun MainContent() {
Surface(modifier = Modifier.fillMaxSize()) {
Column() {
SearchBox()
CurrentWeather()
WindAndHumidityBox()
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeweathertestTheme {
// A surface container using the 'background' color from the theme
Surface(
color = MaterialTheme.colors.background,
modifier = Modifier.fillMaxSize()
) {
MainContent()
}
}
}
}
}
Also the PURPLE portion is using this code.
Surface(
modifier = Modifier
.padding(40.dp).wrapContentHeight(), elevation = 3.dp, shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colors.primarySurface
) {
In XML we could use wrap content and apply padding to it, this doesn't seem to be the case with compose? I am trying to do something like this
EDIT: Whole compose file
#Composable
private fun Content() {
Column(modifier = Modifier.fillMaxSize()) {
SearchBox()
CurrentWeather()
WindAndHumidityBox()
}
}
#Composable
fun WindAndHumidityBox() {
Surface(
modifier = Modifier
.padding(40.dp)
.wrapContentHeight(), elevation = 3.dp, shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colors.primarySurface
) {
Row {
Row(modifier = Modifier.align(Alignment.CenterVertically)) {
Image(
painter = painterResource(id = R.drawable.day_clear),
contentDescription = "humidity"
)
Text(
text = "Precipitation \n 10%", fontWeight = FontWeight.Bold, fontSize = 20.sp,
modifier = Modifier.align(Alignment.CenterVertically)
)
}
Row(modifier = Modifier.align(Alignment.CenterVertically)) {
Image(
painter = painterResource(id = R.drawable.day_clear),
contentDescription = "humidity"
)
Text(
text = "Precipitation \n 10%", fontWeight = FontWeight.Bold, fontSize = 20.sp,
modifier = Modifier.align(Alignment.CenterVertically)
)
}
}
}
}
#Composable
private fun CurrentWeather() {
Box(modifier = Modifier.fillMaxWidth()) {
Column(Modifier.align(Alignment.Center)) {
Column(modifier = Modifier.padding(bottom = 20.dp)) { // location and time/date
Row(modifier = Modifier.align(Alignment.CenterHorizontally)) {
Icon(
painter = painterResource(id = R.drawable.ic_location),
contentDescription = "location"
)
Text(
text = "London", fontWeight = FontWeight.Bold, fontSize = 20.sp,
modifier = Modifier.align(Alignment.CenterVertically)
)
}
Text(text = "Thu 4 December 8:41 am")
}
Row(Modifier.align(Alignment.CenterHorizontally)) {
Image(
painterResource(id = R.drawable.day_clear),
modifier = Modifier.align(alignment = Alignment.CenterVertically),
contentDescription = "current weather image displaying the current weather"
)
Text(
text = "27", fontSize = 40.sp, modifier = Modifier
.padding(5.dp)
.align(Alignment.Top)
)
}
Text(
text = "Sunny",
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = 20.dp),
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
}
}
}
#Composable
private fun SearchBox() {
Box {
var textValue by remember { mutableStateOf("") }
val context = LocalContext.current
OutlinedTextField(value = textValue,
leadingIcon = {
Icon(
painterResource(id = R.drawable.ic_baseline_search_24),
"search"
)
},
label = { Text("Search For A City") },
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Search,
keyboardType = KeyboardType.Text
),
keyboardActions = KeyboardActions(
onSearch = {
hideKeyboard(context = context)
}),
onValueChange = { text ->
textValue = text
}
)
}
}
You are using too many parent containers.
Just use:
Surface(
color = MaterialTheme.colors.background,
modifier = Modifier.fillMaxSize()
){
Column(){
WindAndHumidityBox()
}
}
Then you can achieve the PURPLE portion in many ways.
In particular check the Intrinsic measurements.
For example:
Surface(
modifier = Modifier
.padding(horizontal = 16.dp)
.fillMaxWidth(),
elevation = 3.dp,
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colors.primarySurface
) {
Row(
Modifier.padding(40.dp), //Padding inside the Row
horizontalArrangement = Arrangement.Center
) {
Row(modifier = Modifier
.align(Alignment.CenterVertically)
.height(IntrinsicSize.Min) //Intrinsic measurements to center the icon vertically
) {
Image(
modifier = Modifier.fillMaxHeight(),
//..
)
//...
}
//...
}
}
I have the following composable function to build a Chip:
#Composable
fun CategoryChip(
category: String,
isSelected: Boolean = false,
onSelectedCategoryChanged: (String) -> Unit,
onExecuteSearch: () -> Unit
) {
Surface(
modifier = Modifier.padding(end = 8.dp, bottom = 8.dp),
elevation = 8.dp,
shape = RoundedCornerShape(16.dp),
color = when {
isSelected -> colorResource(R.color.teal_200)
else -> colorResource(R.color.purple_500)
}
) {
Row(modifier = Modifier
.toggleable(
value = isSelected,
onValueChange = {
onSelectedCategoryChanged(category)
onExecuteSearch()
}
)) {
Text(
text = category,
style = MaterialTheme.typography.body2,
color = Color.White,
modifier = Modifier.padding(8.dp)
)
}
}
}
This creates the following chip:
But what I am trying to achieve is the following:
Is it possible to create a shape like that with Jetpack Compose?
Starting with M2 1.2.0-alpha02 you can use the Chip or FilterChip composable:
Chip(
onClick = { /* Do something! */ },
border = BorderStroke(
ChipDefaults.OutlinedBorderSize,
Color.Red
),
colors = ChipDefaults.chipColors(
backgroundColor = Color.White,
contentColor = Color.Red
),
leadingIcon = {
Icon(
Icons.Filled.Settings,
contentDescription = "Localized description"
)
}
) {
Text("Change settings")
}
With M3 (androidx.compose.material3) you can use one of these options:
AssistChip
FilterChip
InputChip
SuggestionChip
Something like:
AssistChip(
onClick = { /* Do something! */ },
label = { Text("Assist Chip") },
leadingIcon = {
Icon(
Icons.Filled.Settings,
contentDescription = "Localized description",
Modifier.size(AssistChipDefaults.IconSize)
)
}
)
Yes, all you have to do is add a border to your surface.
Surface(
modifier = Modifier.padding(end = 8.dp, bottom = 8.dp),
elevation = 8.dp,
shape = RoundedCornerShape(16.dp),
border = BorderStroke(
width = 1.dp,
color = when {
isSelected -> colorResource(R.color.teal_200)
else -> colorResource(R.color.purple_500)
}
)
)
Building on Code Poet's answer i wanted to show how to do a Material Chip with background color:
#Composable
fun buildChip(label: String, icon: ImageVector? = null) {
Box(modifier = Modifier.padding(8.dp)) {
Surface(
elevation = 1.dp,
shape = MaterialTheme.shapes.small,
color = Color.LightGray
) {
Row(verticalAlignment = Alignment.CenterVertically) {
if (icon != null) Icon(
icon,
modifier = Modifier
.fillMaxHeight()
.padding(horizontal = 4.dp)
)
Text(
label,
modifier = Modifier.padding(8.dp),
style = MaterialTheme.typography.button.copy(color = Color.DarkGray)
)
}
}
}
}
Simply use ChipDefaults.outlinedBorder and Defaults.outlinedChipColors():
Chip(
onClick = {},
border = ChipDefaults.outlinedBorder,
colors = ChipDefaults.outlinedChipColors(),
) {
Text(
text = "Trends",
)
}
compose version 1.2.1 , kotlinCompilerExtensionVersion 1.3.1
Also add accompanist Flow library
implementation
"com.google.accompanist:accompanist-flowlayout:0.26.4-beta"
We will use SuggestionChip composable function to create chips.
#Composable
fun SuggestionChipLayout() {
val chips by remember { mutableStateOf(listOf("India", "France", "Spain","Netherland","Austarlia","Nepal")) }
var chipState by remember { mutableStateOf("") }
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(text = "Suggestion Chip Example")
Spacer(modifier = Modifier.height(20.dp))
FlowRow(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp),
mainAxisSpacing = 16.dp,
crossAxisSpacing = 16.dp,
) {
chips.forEach {
SuggestionChipEachRow(chip = it, it == chipState) { chip ->
chipState = chip
}
}
}
}
}
#OptIn(ExperimentalMaterial3Api::class)
#Composable
fun SuggestionChipEachRow(
chip: String,
selected: Boolean,
onChipState: (String) -> Unit
) {
SuggestionChip(onClick = {
if (!selected)
onChipState(chip)
else
onChipState("")
}, label = {
Text(text = chip)
},
border = SuggestionChipDefaults.suggestionChipBorder(
borderWidth = 1.dp,
borderColor = if (selected) Color.Transparent else PurpleGrey40
),
modifier = Modifier.padding(horizontal = 16.dp),
colors = SuggestionChipDefaults.suggestionChipColors(
containerColor = if (selected) Purple80 else Color.Transparent
),
shape = RoundedCornerShape(16.dp)
)
}
Filter Chips: In filter chip we can select multiple items at a time
compose version 1.2.1 , kotlinCompilerExtensionVersion 1.3.1 Also add accompanist Flow library
implementation
"com.google.accompanist:accompanist-flowlayout:0.26.4-beta"
we will use FilterChip composable function to create Filter Chip
#SuppressLint("MutableCollectionMutableState")
#Composable
fun FilterChipLayout() {
val originalChips by remember {
mutableStateOf(
listOf(
"chip1",
"chip2",
"chip3",
"chip4",
"chip5"
)
)
}
val temp: Set<Int> = emptySet()
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(text = "Filter Chip Example")
Spacer(modifier = Modifier.height(20.dp))
FilterChipEachRow(chipList = originalChips, tempList = temp)
}
}
#OptIn(ExperimentalMaterial3Api::class)
#Composable
fun FilterChipEachRow(
chipList: List<String>,
tempList: Set<Int>
) {
var multipleChecked by rememberSaveable { mutableStateOf(tempList) }
FlowRow(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp),
mainAxisSpacing = 16.dp,
crossAxisSpacing = 16.dp,
) {
chipList.forEachIndexed { index, s ->
FilterChip(selected = multipleChecked.contains(index), onClick = {
multipleChecked = if (multipleChecked.contains(index))
multipleChecked.minus(index)
else
multipleChecked.plus(index)
}, label = {
Text(text = s)
},
border = FilterChipDefaults.filterChipBorder(
borderColor = if (!multipleChecked.contains(index)) PurpleGrey40 else Color.Transparent,
borderWidth = if (multipleChecked.contains(index)) 0.dp else 2.dp
),
shape = RoundedCornerShape(8.dp),
leadingIcon = {
(if (multipleChecked.contains(index)) Icons.Default.Check else null)?.let {
Icon(
it,
contentDescription = ""
)
}
}
)
}
}
}
I want to create Cardview using jetpack compose but i am not able to find any
example.
You can use something like:
Card(
shape = RoundedCornerShape(8.dp),
backgroundColor = MaterialTheme.colors.surface,
) {
Column(
modifier = Modifier.height(200.dp).padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(text = "This is a card view",
style = MaterialTheme.typography.h4)
}
}
With Material3 you can use:
Card(
shape = RoundedCornerShape(8.dp),
colors = CardDefaults.cardColors(containerColor = /* ... */)
)
in v0.1.0-dev09 version, can be done like this, where the padding of Card sets the margin of the card, the padding of Box sets the padding inside the card.
Card(
shape = RoundedCornerShape(8.dp),
modifier = Modifier.padding(16.dp).fillMaxWidth()
) {
Box(modifier = Modifier.height(200.dp).padding(16.dp)) {
Text("This is a card view")
}
}
As the friends recommended, Card is a way of creating CardView but you can do that by surface too :
val shape = RoundedCornerShape(10.dp)
Surface(modifier = Modifier.size(250.dp, 70.dp), elevation = 8.dp, shape = shape) {
Text(text = "Sample text")
}
Note that Surface and Card cannot be used for positioning items so that if you wanna position that Text(text = "Sample text") , you should use one layout inside that Surface like this :
val shape = RoundedCornerShape(10.dp)
Surface(modifier = Modifier.size(250.dp, 70.dp), elevation = 8.dp, shape = shape) {
Box(modifier = Modifier.fillMaxSize()) {
Text(modifier = Modifier.align(Alignment.Center), text = "Sample text")
}
}
The appropriate way for creating CardView is this but if you wanna just create shadow for a view, you can use Modifier.shadow (Note that Modifier.shadow and Surface/Card are not the same):
Box(modifier = Modifier.size(250.dp, 70.dp).shadow(8.dp, RoundedCornerShape(10.dp)), contentAlignment = Alignment.Center) {
Text(text = "Sample Text")
}
Code:
class ImageCardActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val painter = painterResource(id = R.drawable.grogu)
val contentDescription = "Grogu says hi"
val title = "Force is strong with Grogu"
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier.fillMaxWidth(0.5f)
) {
ImageCard(
title = title,
contentDescription = contentDescription,
painter = painter
)
}
}
}
}
}
#Composable
fun ImageCard(
title: String,
contentDescription:String,
painter: Painter,
modifier:Modifier=Modifier
){
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
elevation = 5.dp
) {
Box(
modifier = Modifier.height(200.dp)
) {
// Image
Image(
painter = painter,
contentDescription = contentDescription,
contentScale = ContentScale.Crop
)
// Gradient
Box(
modifier = Modifier
.fillMaxSize()
.background(
brush = Brush.verticalGradient(
colors = listOf(
Color.Transparent, Color.Black
),
startY = 300f
)
)
)
// Title
Box(
modifier = Modifier
.fillMaxSize()
.padding(12.dp),
contentAlignment = Alignment.BottomStart
) {
Text(
text = title,
style = TextStyle(color = Color.White, fontSize = 12.sp)
)
}
}
}
}