How can I align different items inside LazyColumn in jetpackCompose - android

I am building a chat app with firebase and I need to align the chat bubbles in the end when I write the message and in the start when I receive, like in whatsapp. If I use the horizontalArrangement in the lazyColumn it affects all the items. I tried using the modifier.align in the chat bubbles but nothing happens. How can I do this?
below is my lazyColumn
LazyColumn(
modifier = Modifier.fillMaxWidth(),
) {
if (list != null && list.isNotEmpty()) {
items(items = list) {
if (it.user1id == args.userId) {
ChatCard(
message = it,
color = Color.Magenta,
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(
start = 32.dp,
end = 4.dp,
top = 4.dp
)
)
} else {
ChatCard(
message = it,
color = Color.White,
Modifier.padding(
start = 4.dp,
end = 32.dp,
top = 4.dp
)
)
}
}
}
}
#Composable
fun ChatCard(message: Message, color: Color, modifier: Modifier = Modifier){
Card(
modifier = modifier,
backgroundColor = color,
shape = RoundedCornerShape(10.dp)
) {
Row(
modifier = Modifier.padding(4.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
modifier = Modifier
.padding(4.dp)
.widthIn(0.dp, 280.dp),
text = message.message
)
Text(
modifier = Modifier.padding(4.dp),
text = message.time,
style = TextStyle(
fontSize = 12.sp,
color = Color.LightGray
)
)
}
}
}

You can add a Row for each item applying a different horizontalArrangement removing the Modifier.align in your Card.
Something like:
items(items = itemsList) {
Row(Modifier.fillMaxWidth(),
horizontalArrangement = if (it == ....)
Arrangement.Start else
Arrangement.End) {
if (it == ....) {
ChatCard(
color = Color.Magenta,
modifier = Modifier
.padding(
start = 32.dp,
end = 4.dp,
top = 4.dp
)
)
} else {
ChatCard(
color = Color.White,
Modifier.padding(
start = 4.dp,
end = 32.dp,
top = 4.dp
)
)
}
}

Related

Why is floating action button ttransparent even though it is colored and showing the list behind it Jetpack Compose

I have lazy list and a floating action button in the bottom end, the FAB has a color. But the floating action button in jetpack compose is showing the list in the background even thought it has a color. Even after adding the elevation it is not working. How to solve it?
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
) {
androidx.compose.material3.FloatingActionButton(
containerColor = appColors.primary,
contentColor = appColors.primary,
elevation = FloatingActionButtonDefaults.elevation(8.dp),
shape = CircleShape,
onClick = {},
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp),
) {
Icon(Icons.Filled.Add, null, tint = Color.White)
}
if (viewModel.state.value.patientsList.isEmpty()) {
Text(
text = "No Patients Available",
style = FontLibrary.regularBody16(textAlign = TextAlign.Center)
)
} else {
LazyColumn(
modifier = Modifier
.padding(start = 8.dp, end = 8.dp)
.fillMaxSize()
) {
items(
items = viewModel.state.value.patientsList,
key = { patient ->
patient.id
}
) { patient ->
PatientCard(patient)
Divider(color = appColors.secondary, thickness = 1.dp)
}
}
}
}
In Jetpack compose UI components are placed in the order as you place them, so in box you have first placed Floating action button, and then the list.
You should place FAB in the end, i.e., move its code to the bottom.
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
) {
if (viewModel.state.value.patientsList.isEmpty()) {
Text(
text = "No Patients Available",
style = FontLibrary.regularBody16(textAlign = TextAlign.Center)
)
} else {
LazyColumn(
modifier = Modifier
.padding(start = 8.dp, end = 8.dp)
.fillMaxSize()
) {
items(
items = viewModel.state.value.patientsList,
key = { patient ->
patient.id
}
) { patient ->
PatientCard(patient)
Divider(color = appColors.secondary, thickness = 1.dp)
}
}
}
androidx.compose.material3.FloatingActionButton(
containerColor = appColors.primary,
contentColor = appColors.primary,
shape = CircleShape,
onClick = {},
modifier = Modifier
.align(BottomEnd)
.padding(16.dp),
) {
Icon(Icons.Filled.Add, null, tint = Color.White)
}
}

Expandable FAB going through bottom nav bar - Jetpack Compose

I made an expandable floating action button like
here
i want to make it expand verticly and reveal to more buttons, when its note docked to bottom navigation bar, every thing is ok but when i make it docked it's going through bottom nav bar,
When not expanded looking like this
but when expanded like this
How can i make it expand properly
and i also want to align all 3 circle buttons horizontaly.
Thank you so much!
Code:
#Composable
fun ExpandableFAB(
modifier: Modifier = Modifier,
onFabItemClicked: (fabItem: ExpandableFABMenuItem) -> Unit,
menuItems: List<ExpandableFABMenuItem> = ExpandableFABMenuItem.expandableFabMenuItems
) {
var expandedState by remember { mutableStateOf(false) }
val rotationState by animateFloatAsState(
targetValue = if (expandedState) 45f else 0f
)
Column(
modifier = modifier.wrapContentSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
AnimatedVisibility(
visible = expandedState,
enter = fadeIn() + expandVertically(),
exit = fadeOut()
) {
LazyColumn(
modifier = Modifier.wrapContentSize(),
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.spacedBy(15.dp)
) {
items(menuItems.size) { index ->
ExpandableFABItem(
item = menuItems[index],
onFabItemClicked = onFabItemClicked
)
}
item {}
}
}
FloatingActionButton(
onClick = { expandedState = !expandedState },
backgroundColor = Blue
) {
Icon(
imageVector = Icons.Outlined.Add,
contentDescription = "FAB",
modifier = Modifier.rotate(rotationState),
)
}
}
}
#Composable
fun ExpandableFABItem(
item: ExpandableFABMenuItem,
onFabItemClicked: (item: ExpandableFABMenuItem) -> Unit
) {
Row(
modifier = Modifier
.wrapContentSize()
.padding(end = 10.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = item.label,
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.background(MaterialTheme.colors.surface)
.padding(horizontal = 6.dp, vertical = 4.dp)
)
Box(
modifier = Modifier
.clip(CircleShape)
.size(42.dp)
.clickable { onFabItemClicked }
.background(Blue),
contentAlignment = Alignment.Center
) {
Icon(
imageVector = item.icon,
contentDescription = "Create New Note",
tint = White
)
}
}
}

Why onboarding button not work in jetpack compose?

I am new in jetpack compose, and I am try to learn it, so I have simple onboarding screen in jetpack compose, when I update project to jetpack compose 1.1.1 , "Next" button not working for onboarding screen to scroll horizontally. it was working when I use jetpack compose 1.0.0 version, I do not know what change in new version, any idea?
#ExperimentalPagerApi
#Composable
fun OnBoardScreen() {
val scaffoldState = rememberScaffoldState()
val onBoardViewModel : OnBoardViewModel = viewModel()
val context = LocalContext.current
val currentPage = onBoardViewModel.currentPage.collectAsState()
Toast.makeText(context, "${currentPage.value}", Toast.LENGTH_SHORT).show()
val pagerState = rememberPagerState(
pageCount = onBoardItem.size,
initialOffscreenLimit = 2,
initialPage = 0,
infiniteLoop = false
)
Scaffold(
modifier = Modifier.fillMaxSize(),
scaffoldState = scaffoldState
) {
Surface(
modifier = Modifier.fillMaxSize()
) {
LaunchedEffect(scaffoldState.snackbarHostState){
pagerState.animateScrollToPage(
page = currentPage.value
)
}
Box(
modifier = Modifier
.fillMaxWidth()
.background(Gray200)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
HorizontalPager(
state = pagerState
) { page ->
Column(
modifier = Modifier
.padding(top = 65.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = onBoardItem[page].image),
contentDescription = "OnBoardImage",
modifier = Modifier
.size(250.dp)
)
Text(
text = onBoardItem[page].title,
modifier = Modifier
.padding(top = 50.dp),
color = Color.White,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
Text(
text = onBoardItem[page].desc,
modifier = Modifier
.padding(30.dp),
color = Color.White,
fontSize = 18.sp,
textAlign = TextAlign.Center
)
}
}
PagerIndicator(onBoardItem.size, pagerState.currentPage)
}
Box(
modifier = Modifier
.align(Alignment.BottomCenter)
) {
Row(
modifier = Modifier
.padding(bottom = 20.dp)
.fillMaxWidth(),
horizontalArrangement = if (pagerState.currentPage != 2 ) {
Arrangement.SpaceBetween
} else {
Arrangement.Center
}
) {
if (pagerState.currentPage == 2) {
OutlinedButton(
onClick = {
Toast.makeText(context, "Start the Screen", Toast.LENGTH_SHORT).show()
},
shape = RoundedCornerShape(45.dp)
) {
Text(
text = "Get Started",
modifier = Modifier.padding(
vertical = 8.dp,
horizontal = 40.dp
),
color = Color.Black
)
}
} else {
Text(
text = "Skip",
color = Color.White,
modifier = Modifier.padding(start = 20.dp),
fontSize = 18.sp,
fontWeight = FontWeight.Medium
)
Text(
text = "Next",
color = Color.White,
modifier = Modifier
.clickable {
onBoardViewModel.setCurrentPage(pagerState.currentPage + 1)
}
.padding(end = 20.dp),
fontSize = 18.sp,
fontWeight = FontWeight.Medium
)
}
}
}
}
}
}
}
It looks like you expect these lines to scroll the pager every time you change the value of currentPage:
LaunchedEffect(scaffoldState.snackbarHostState) {
pagerState.animateScrollToPage(
page = currentPage.value
)
}
But scaffoldState.snackbarHostState in this scope is a static value, which means LaunchedEffect is not gonna be relaunched.
One option is to pass currentPage instead, but also, as your currentPage is backed by flow, it's cleaner to collect it:
LaunchedEffect(Unit) {
onBoardViewModel.currentPage
.collect {
pagerState.animateScrollToPage(
page = currentPage.value
)
}
}
p.s.
Also, when you need to make a text button, instead of adding clickable to the Text you can use TextButton:
TextButton(
onClick = {
}
) {
Text(/*...*/)
}

Constraining a Composable to the bottom of a Column

Me and my team are new to Compose and we're trying to build a TopUp screen for a client. The screen consists of a Column that contains some Padding (in the form of a Composable) for the TopAppBar, two Card composables, a button, then a footer composable which I need to constraint to the bottom of the column, and finally, some padding (again in the form of a composable) to give us some space between the content and the bottom navbar.
Right now we're using a spacer with a fixed dp value but obviously, this won't scale so that it is constrained to the bottom on all devices. What would be the best way to go about achieving such a look?
screen composable:
#OptIn(ExperimentalComposeUiApi::class)
#Composable
fun TopUpScreen() {
Column(
horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(horizontal = 16.dp)
) {
val viewModel = getViewModel<TopUpViewModel>()
TopBarPadding()
TopUpCardView(title = stringResource(id = R.string.choose_topup_amount)) {
var selectedCardIndex by remember { mutableStateOf(-1) }
Row(
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
) {
Card(
shape = RoundedCornerShape(11.dp),
elevation = if (selectedCardIndex == 0) 1.dp else 0.dp,
backgroundColor = if (selectedCardIndex == 0) colorResource(id = R.color.bottom_modal_drawer_background) else colorResource(
id = R.color.more_screen_item_background
),
modifier = Modifier
.width(71.dp)
.height(56.dp)
.shadow(
if (selectedCardIndex == 0) 8.dp else 0.dp,
shape = RoundedCornerShape(11.dp)
)
.clickable {
selectedCardIndex = 0
viewModel.topUpAmount = 20.0
}
) {
Text(
"€20",
fontSize = 16.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center,
modifier = Modifier.wrapContentHeight()
)
}
Card(
shape = RoundedCornerShape(11.dp),
elevation = if (selectedCardIndex == 1) 1.dp else 0.dp,
backgroundColor = if (selectedCardIndex == 1) colorResource(id = R.color.bottom_modal_drawer_background) else colorResource(
id = R.color.more_screen_item_background
),
modifier = Modifier
.width(71.dp)
.height(56.dp)
.shadow(
if (selectedCardIndex == 1) 8.dp else 0.dp,
shape = RoundedCornerShape(11.dp)
)
.clickable {
selectedCardIndex = 1
viewModel.topUpAmount = 40.0
}
) {
Text(
"€40",
fontSize = 16.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center,
modifier = Modifier.wrapContentHeight()
)
}
Card(
shape = RoundedCornerShape(11.dp),
elevation = if (selectedCardIndex == 2) 1.dp else 0.dp,
backgroundColor = if (selectedCardIndex == 2) colorResource(id = R.color.bottom_modal_drawer_background) else colorResource(
id = R.color.more_screen_item_background
),
modifier = Modifier
.width(71.dp)
.height(56.dp)
.shadow(
if (selectedCardIndex == 2) 8.dp else 0.dp,
shape = RoundedCornerShape(11.dp)
)
.clickable {
selectedCardIndex = 2
viewModel.topUpAmount = 70.0
}
) {
Text(
"€70",
fontSize = 16.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center,
modifier = Modifier.wrapContentHeight()
)
}
Card(
shape = RoundedCornerShape(11.dp),
elevation = if (selectedCardIndex == 3) 1.dp else 0.dp,
backgroundColor = if (selectedCardIndex == 3) colorResource(id = R.color.bottom_modal_drawer_background) else colorResource(
id = R.color.more_screen_item_background
),
modifier = Modifier
.width(71.dp)
.height(56.dp)
.shadow(
if (selectedCardIndex == 3) 8.dp else 0.dp,
shape = RoundedCornerShape(11.dp)
)
.clickable {
selectedCardIndex = 3
viewModel.topUpAmount = 100.0
}
) {
Text(
"€100",
fontSize = 16.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Center,
modifier = Modifier.wrapContentHeight()
)
}
}
}
Spacer(modifier = Modifier.padding(16.dp))
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
TopUpCardView(title = stringResource(id = R.string.enter_custom_topup_amount)) {
var customAmountTxt by remember { mutableStateOf(TextFieldValue()) }
TextField(
value = customAmountTxt,
onValueChange = {
customAmountTxt = it
},
maxLines = 1,
singleLine = true,
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.ic_euro),
contentDescription = stringResource(
R.string.euro_icon_desc
),
modifier = Modifier.padding(
start = 16.dp,
end = 16.dp,
top = 12.dp,
bottom = 12.dp
)
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(onDone = {
focusManager.clearFocus()
keyboardController?.hide()
}),
shape = RoundedCornerShape(6.dp),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = colorResource(id = R.color.white),
textColor = colorResource(id = R.color.black),
focusedIndicatorColor = colorResource(id = R.color.white),
unfocusedIndicatorColor = colorResource(id = R.color.white),
disabledIndicatorColor = colorResource(id = R.color.white),
cursorColor = colorResource(id = R.color.black)
),
textStyle = TextStyle(
color = Color.Black,
fontSize = 16.sp,
fontWeight = FontWeight.Normal,
textAlign = TextAlign.Start
),
modifier = Modifier
.height(50.dp)
.fillMaxWidth()
.shadow(8.dp, shape = RoundedCornerShape(6.dp))
)
}
Spacer(modifier = Modifier.padding(32.fixedDp()))
val context = LocalContext.current //todo:sp remove when you remove the toast
MyButton(
text = stringResource(id = R.string.continue_text),
buttonType = MyButtonType.PRIMARY,
onClick = {
Toast.makeText(context, "[TODO] Navigate to card screen", Toast.LENGTH_SHORT).show()
})
//todo:sp replace the spacer implementation with something that will constraint the
// footer to the bottom as it should
Spacer(modifier = Modifier.height(130.dp))
AcceptedCardsFooter()
BottomBarPadding()
}
}
TopUpCardView:
#Composable
fun TopUpCardView(
title: String,
modifier: Modifier = Modifier,
mainBody: #Composable () -> Unit
) {
Card(
shape = RoundedCornerShape(13.dp),
elevation = 10.dp,
modifier = modifier
.fillMaxWidth()
.height(131.dp)
) {
Column(modifier = Modifier.padding(vertical = 20.dp, horizontal = 16.dp)) {
Text(
text = title,
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Start
)
Spacer(modifier = Modifier.padding(9.dp))
mainBody()
}
}
}
Footer:
#Composable
fun AcceptedCardsFooter(isTransparent: Boolean = false) {
Row(modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.background(
if (isTransparent) {
Color.Transparent
} else {
colorResource(id = R.color.registration_note_background)
}
)
.padding(bottom = 12.dp, top = 12.dp, start = 16.dp, end = 14.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = LocalContext.current.getString(R.string.accepted_cards),
fontSize = 12.sp,
color = colorResource(id = R.color.Black_100)
)
Row(verticalAlignment = Alignment.CenterVertically) {
Image(painter = painterResource(id = R.drawable.visa), contentDescription = "")
Spacer(modifier = Modifier.padding(17.fixedDp()))
Image(painter = painterResource(id = R.drawable.mastercard), contentDescription = "")
Spacer(modifier = Modifier.padding(10.fixedDp()))
Image(painter = painterResource(id = R.drawable.american_express), contentDescription = "")
}
}
}
The easiest way is to use weight modifier:
Spacer(modifier = Modifier.height(130.dp).weight(1f))
Add bottom padding to first Column for give space between content and bottombar. After that give weight to second Column for make footer constraint to the bottom.
For example,
Column(
modifier = Modifier.fillMaxSize().padding(bottom = 15.dp, start = 16.dp, end = 16.dp )
) {
Column(
modifier = Modifier.fillMaxSize().weight(1f).padding(horizontal = 16.dp)
) {
// top bar
// two cards
// button
}
// add footer here
}
I would use a ConstraintLayout and wrap the view you need to always be at the bottom of the screen.
ConstraintLayout {
// Create references for the composables to constrain
val id_of_your_footer = createRefs()
YourFooterComposable(
modifier = Modifier.constrainAs(id_of_your_footer) {
bottom.linkTo(parent.bottom)
}
)
}
As long as the parent is the root view, the Footer will be constrained to stay at the bottom of the screen.
Alternatively, you can use a scaffold that has these constraints set automatically:
Scaffold(topBar={//place a top bar composable here},
content={//all your content composables here},
bottomBar={//your footer composable here})

How to get Image with text on top/infront? (Google Classroom Home Image Format)

I want to make an Image with Text on top, just like Google CLassroom. But first I want to test Image and then Text. Instead, I got the image overlapping the text. Image Overlapping text
Then I move the Image code after the text. How to get simple G classroom format
Text then Image
#Composable
fun ClassImage(
// icon: VectorAsset,
// label: String,
// modifier: Modifier = Modifier
) {
val imageAlpha = 1f
Surface(
modifier = Modifier
.padding(start = 8.dp, top = 8.dp, end = 8.dp)
.fillMaxWidth(),
color = colors.primary.copy(alpha = 0.12f)
) {
TextButton(
onClick = {},
modifier = Modifier.fillMaxWidth()
) {
Row(
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth())
{
Image(
imageResource(id = R.drawable.class1),
alpha = imageAlpha
)
Column {
Text("Alfred Sisley", fontWeight = FontWeight.Bold)
ProvideEmphasis(emphasis = EmphasisAmbient.current.medium) {
Text("3 minutes ago", style = MaterialTheme.typography.body2)
}
}
}
}
}
}
To put Text on top of the Image you can use Box, which is similar to old FrameLayout.
I'm not sure want you wanted to achieve, but if smth like this:
Then you can do it this way:
Surface(
shape = RoundedCornerShape(8.dp),
modifier = Modifier
.preferredHeight(128.dp)
.clickable(onClick = {})
) {
Box {
Image(
vectorResource(id = R.drawable.ic_launcher_background),
alpha = imageAlpha,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
Column(modifier = Modifier.padding(16.dp)) {
Text(
"Alfred Sisley",
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.h6)
ProvideEmphasis(emphasis = EmphasisAmbient.current.medium) {
Text("3 minutes ago", style = MaterialTheme.typography.body2)
}
Spacer(modifier = Modifier.weight(1f))
Text(text = "Footer", style = MaterialTheme.typography.body1)
}
}
}
With 1.0.0-beta02 you can use a Box as parent container.
Something like:
Box(modifier = Modifier.height(IntrinsicSize.Max))
{
Image(
painterResource(id = R.drawable.xx),
"contentDescription",
alpha = 0.8f,
modifier = Modifier.requiredHeight(100.dp)
)
Column(
modifier = Modifier.fillMaxHeight(),
verticalArrangement = Arrangement.Bottom) {
Text("Alfred Sisley",
fontWeight = FontWeight.Bold)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text("3 minutes ago", style = MaterialTheme.typography.body2)
}
}
}

Categories

Resources