I am using LazyColumn in my #Compsoable screen. Inside LazyColumn there are so many child and which align verticalArrangement = Arrangement.Top and horizontalAlignment = Alignment.CenterHorizontally. But in one child Item I want to use from Start. Can we do that?
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally,
) {
item {
ommonContent()
}
item {
HoldDescription()
}
item {
WarningMessage()
}
item {
Devices() // change this item from Start..
}
// more item in here
}
Expected Output
I tried with these answer to Modifier.align(Alignment.Start) but it gives me error
#Composable
fun Devices(
isEmpty: Boolean,
) {
AnimatedVisibility(
isEmpty,
modifier = Modifier.align(Alignment.Start)
) {
Text()
}
}
Error in Image
To apply the align modifier you can scope your composable with the required scope.
You can use:
#Composable
fun ColumnScope.Devices(
isEmpty: Boolean,
) {
AnimatedVisibility(
isEmpty,
modifier = Modifier.fillMaxWidth().align(Alignment.Start)
) {
Text("xxx")
}
}
Otherwise you can use:
#Composable
fun Devices(
modifier: Modifier,
isEmpty: Boolean,
) {
AnimatedVisibility(
isEmpty,
modifier = modifier
) {
Text("xxx")
}
}
and then
item(){
Column() {
Devices(
modifier = Modifier.fillMaxWidth().align(Alignment.Start),
isEmpty = true)
}
}
Related
I have a LazyColumn with expandable items. And when i click on the item he expands or collapses, but i need that when i click on closed element it opens and others in the list close.(the one that open). So first i moved state of item from remember variable in the item's composable function to the list of dataClass elements. And when i click on item he execute callback that change value of it' selement in the list, but it doesn't recompose.
#Preview
#Composable
fun ExpandableCardList() {
val list = remember { mutableStateListOf(PointsCard(0),PointsCard(1),PointsCard(2),PointsCard(3),PointsCard(4),PointsCard(5))}
val state = rememberLazyListState()
Scaffold { paddingValues ->
LazyColumn(
state = state,
modifier = Modifier
.fillMaxWidth(),
contentPadding = paddingValues
) {
items(list, {it.key}) { item ->
ExpandableCard(
expanded = item.state,
state = {
bool -> item.state = bool
}
)
}
}
}
}
#Composable
fun ExpandableCard(expanded: Boolean, state: (bool:Boolean) -> Unit ){
Card(
Modifier
.fillMaxWidth()
.clickable { state(!expanded) }
.background(Color(Color.BLACK))
) {
Column(Modifier.background(Color(Color.BLACK)))
{
Box(
Modifier
.fillMaxWidth()
.height(54.dp)
.background(Color(Color.BLACK))
)
AnimatedVisibility(expanded) {
Box(
Modifier
.fillMaxWidth()
.padding(start = 10.dp)
.heightIn(56.dp, 300.dp)
.background(Color(Color.BLACK), shape = RoundedCornerShape(bottomStart = 8.dp)
)
)
}
}
}
}
data class PointsCard(
val key: Int = 0,
var state: Boolean = false
)
If you want a single selection, you should probably consider hoisting your list in a class and perform all the structural changes via the list's iterator.
class CardListState {
val list = mutableStateListOf(PointsCard(0),PointsCard(1),PointsCard(2),PointsCard(3),PointsCard(4),PointsCard(5))
fun onSelected(isSelected: Boolean, item: PointsCard) {
val iterator = list.listIterator()
while (iterator.hasNext()) {
val obj = iterator.next()
if (obj.key != item.key) {
iterator.set(obj.copy(state = false))
} else {
iterator.set(obj.copy(state = isSelected))
}
}
}
}
#Composable
fun ExpandableCardList() {
val cardListState = remember { CardListState() }
val state = rememberLazyListState()
Scaffold { paddingValues ->
LazyColumn(
state = state,
modifier = Modifier
.fillMaxWidth(),
contentPadding = paddingValues
) {
items(cardListState.list, {it.key} ) { item ->
ExpandableCard(
expanded = item.state,
state = { bool ->
cardListState.onSelected(bool, item)
}
)
}
}
}
}
#Composable
fun ExpandableCard(
expanded: Boolean,
state: (bool:Boolean) -> Unit
) {
Card(
Modifier
.fillMaxWidth()
.clickable {
state(!expanded)
}
.background(Color.Black)
) {
Column(Modifier.background(Color.Black))
{
Box(
Modifier
.fillMaxWidth()
.height(54.dp)
.background(Color.Red)
)
AnimatedVisibility(expanded) {
Box(
Modifier
.fillMaxWidth()
.padding(start = 10.dp)
.heightIn(56.dp, 300.dp)
.background(Color.Green)
)
}
}
}
}
I'm trying to build a simple chat screen, with a header, a footer (text field) and the messages part which is a lazycolumn. I've seen many people using such methods like the ones below: (fill parent max height, size etc.)
https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyItemScope
All I can put in lazycolumn modifiers is fillMaxHeight, width or size, if I use fillMaxHeight, it destroys the footer, if I don't use anything, the lazycolumn expands until the bottom of the screen, so it does the same behaviour. What am I doing wrong? Why does it behave like this? I can't put images because I don't have enough reputation...
Here is the full code:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Surface() {
Column(Modifier.background(Color.Green)) {
ProfileCard("Kate", "Available")
Conversation(messages = SampleData.conversationSample)
SimpleTextField()
}
}
}
}
}
#Composable
fun Conversation(messages: List<Message>) {
LazyColumn(
modifier = Modifier
.background(color = MainBg).fillMaxHeight(),
reverseLayout = true,
) {
items(messages) { message ->
MessageCard(message)
}
}
}
#Composable
fun MessageCard(message: Message) {
var isExpanded by remember { mutableStateOf(false) }
Column() {
Text(
text = message.message,
color = com.boradincer.hellojetpack.ui.theme.PrimaryText,
modifier = Modifier
.padding(vertical = 4.dp, horizontal = 16.dp)
.clip(RoundedCornerShape(4.dp))
.background(color = LightBg)
.clickable { isExpanded = !isExpanded }
.padding(horizontal = 8.dp, vertical = 5.dp),
maxLines = if (isExpanded) Int.MAX_VALUE else 2
)
}
}
Apply Modifier.weight(1f) to the LazyColumn
Column(){
Header()
LazyColumn(Modifier.weight(1f)) {
//....
}
Footer()
}
Using fillMaxHeight() the modifier will make the LazyColumn fill the whole available height.
The weight modifier requires a ColumnScope.
In your case use the modifier as parameter:
#Composable
fun Conversation(
modifier: Modifier = Modifier,
messages: List<Message>
){
LazyColumn(modifier) {
//...
}
}
Column(){
//
Conversation(
modifier = Modifier.weight(1f),
messsages = list
) {
//....
}
}
I'm using a column to show a list, the items in the list have the attribute isWeekTopic which is a Boolean, in the list I need to show first those elements that have isWeekTopic = true, and then show those ones that have isWeekTopic = false, the items that has isWeekTopic = true are going to change every week.
I managed to print the ones that has isWeekTopic = true with a header on the design, but I can't make them the first element to show this is my code
#Composable
fun TopicsItemComposable(
modifier: Modifier,
topicsItem: TopicsItemResponseModel,
onItemClicked: (TopicsItemResponseModel) -> Unit
) {
var cardSelected by remember { mutableStateOf(false) }
Card(
modifier = modifier
.clickable {
onItemClicked(topicsItem)
cardSelected = !cardSelected
}
.fillMaxWidth()
.wrapContentHeight(),
shape = RoundedCornerShape(12.dp),
backgroundColor = CYAN
) {
Column(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min),
) {
Column {
if (topicsItem.isWeekTopic){
TopicsItem()
TopicBody(topicsItem)
Row(modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min),) {
TopicIcons(topicsItem)
TopicImage()
}
}
}
Column(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min),
) {
if (!topicsItem.isWeekTopic){
TopicBody(topicsItem)
Row(modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min),) {
TopicIcons(topicsItem)
TopicImage()
}
}
}
}
}
}
I want multiple All LazyColumn scroll simultaneously
I can't use LazyHorizontalGrid or LazyVerticalGrid because of inner layout what two layout is different.
How can i share scrolling in multiple LazyColumn?
#Composable
fun TableScreen2(list: List<Time>, cal: Calendar, df: DateFormat) {
LazyRow(Modifier.fillMaxSize()) {
item {
LazyColumn(
modifier = Modifier
.fillParentMaxHeight()
) {
items(count = list.first().timeList.size / 2) {
Column(
modifier = Modifier
.width(60.dp)
.height(50.dp),
verticalArrangement = Arrangement.Top
) {
Text(df.format(stateCal.time))
stateCal.add(Calendar.MINUTE, 30)
}
}
}
}
items(4) { listIndex ->
LazyColumn(modifier = Modifier.fillParentMaxHeight()) {
itemsIndexed(list[listIndex].timeList) { timeIndex, timeItem ->
Box(
modifier = Modifier
.height(30.dp)
.width(60.dp)
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Text(text = "$timeIndex")
}
}
}
}
}
}
here is gif
A single LazyColumn, where each entry in the lazy column is a row of 5 items looks like it would fit what you want.
A few days ago I bumped on a problem where a part of my view is overlaped by keyboard.
Let's say we have 3 different dialogs (could be any content), which looks like this:
When I want to write in anything, last dialog is covered by keyboard:
And there's no way to see what user wrote. Here's my code:
#Composable
fun BuildWordsView(navController: NavController, sharedViewModel: SharedViewModel) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(PrimaryLight)
.fillMaxSize()
) {
BuildWordsScreenContents()
}
}
#Composable
fun BuildWordsScreenContents() {
Column(
Modifier
.fillMaxSize()
.padding(all = 16.dp)
) {
val inputBoxModifier = Modifier
.clip(RoundedCornerShape(10.dp))
.background(Primary)
.weight(12f)
.wrapContentHeight()
InputBlock("Dialog1", inputBoxModifier)
Spacer(Modifier.weight(1f))
InputBlock("Dialog2", inputBoxModifier)
Spacer(Modifier.weight(1f))
InputBlock("Dialog3", inputBoxModifier)
}
}
#Composable
fun InputBlock(dialogText: String, inputBlockModifier: Modifier) {
Column(modifier = inputBlockModifier) {
Text(
dialogText,
fontSize = 30.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center)
)
var text by remember { mutableStateOf("") }
TextField(
value = text,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center),
onValueChange = { text = it },
label = { Text("Label") }
)
}
}
This question seems to be similar to mine but answers modificate the content of view which I want to avoid:
Software keyboard overlaps content of jetpack compose view
By now I figured out how to solve this problem and I share my approach as an answer
My approach to deal with this problem is using Insets for Jetpack Compose:
https://google.github.io/accompanist/insets/
In order to start dealing with problem you need to add depency to gradle (current version is 0.22.0-rc).
dependencies {
implementation "com.google.accompanist:accompanist-insets:0.22.0-rc"
}
Then you need to wrap your content in your activity with ProvideWindowInsets
setContent {
ProvideWindowInsets {
YourTheme {
//YOUR CONTENT HERE
}
}
}
Additionaly you need to add following line in your activity onCreate() function:
WindowCompat.setDecorFitsSystemWindows(window, false)
Update: Despite this function is recommended, to my experience it may make this approach not work. If you face any problem, you may need to delete this line.
Now your project is set up to use Insets
In the next steps I'm gonna use code I provided in question
First of all you need to wrap your main Column with
ProvideWindowInsets(windowInsetsAnimationsEnabled = true)
Then let's modificate a modifier a bit by adding:
.statusBarsPadding()
.navigationBarsWithImePadding()
.verticalScroll(rememberScrollState())
As you can see the trick in my approach is to use verticalScroll(). Final code of main column should look like this:
#Composable
fun BuildWordsView(navController: NavController, sharedViewModel: SharedViewModel) {
ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(PrimaryLight)
.statusBarsPadding()
.navigationBarsWithImePadding()
.verticalScroll(rememberScrollState())
.fillMaxSize()
) {
BuildWordsScreenContents()
}
}
}
Now let's modificate the modifier of Column in fun BuildWordsScreenContents()
The main modification is that we provide a height of our screen by:
.height(LocalConfiguration.current.screenHeightDp.dp)
This means that height of our Column would fit our screen perfectly. So when keyboard is not opened the Column will not be scrollable
There is the full code:
#Composable
fun BuildWordsView(navController: NavController, sharedViewModel: SharedViewModel) {
ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
Column(
modifier = Modifier
.fillMaxWidth()
.background(PrimaryLight)
.statusBarsPadding()
.navigationBarsWithImePadding()
.verticalScroll(rememberScrollState())
.fillMaxSize()
) {
BuildWordsScreenContents()
}
}
}
#Composable
fun BuildWordsScreenContents() {
Column(
Modifier
.height(LocalConfiguration.current.screenHeightDp.dp)
.padding(all = 16.dp)
) {
val inputBoxModifier = Modifier
.clip(RoundedCornerShape(10.dp))
.background(Primary)
.weight(12f)
.wrapContentHeight()
InputBlock("Dialog1", inputBoxModifier)
Spacer(Modifier.weight(1f))
InputBlock("Dialog2", inputBoxModifier)
Spacer(Modifier.weight(1f))
InputBlock("Dialog3", inputBoxModifier)
}
}
#Composable
fun InputBlock(dialogText: String, inputBlockModifier: Modifier) {
Column(modifier = inputBlockModifier) {
Text(
dialogText,
fontSize = 30.sp,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center)
)
var text by remember { mutableStateOf("") }
TextField(
value = text,
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.Center),
onValueChange = { text = it },
label = { Text("Label") }
)
}
}
The final code allows us to scroll down the view:
Important Note For APIs 30-
For APIs lower then 30 you need to modificate the AndroidManifest.xml file
In <activity you need to add android:windowSoftInputMode="adjustResize" in order to make it work. It do not resize your components but it is obligatory to make this approach work
Manifest should look like this:
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize"
Feel free to give me any tips how can I improve my question. AFAIK this problem is as old as android and I wanted to create a quick tutorial how to manage that. Happy coding!
Here's my solution, using the experimental features in Compose 1.2.0
In build.gradle (:project)
...
ext {
compose_version = '1.2.0-beta03'
}
...
In build.gradle (:app)
...
dependencies {
implementation 'androidx.core:core-ktx:1.8.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation "androidx.compose.foundation:foundation-layout:$compose_version"
...
}
In AndroidManifest.xml
<activity
...
android:windowSoftInputMode="adjustResize" >
In AuthScreen.kt
#OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
#Composable
fun AuthScreen(
val focusManager = LocalFocusManager.current
val coroutineScope = rememberCoroutineScope()
// Setup the handles to items to scroll to.
val bringIntoViewRequesters = mutableListOf(remember { BringIntoViewRequester() })
repeat(6) {
bringIntoViewRequesters += remember { BringIntoViewRequester() }
}
val buttonViewRequester = remember { BringIntoViewRequester() }
fun requestBringIntoView(focusState: FocusState, viewItem: Int) {
if (focusState.isFocused) {
coroutineScope.launch {
delay(200) // needed to allow keyboard to come up first.
if (viewItem >= 2) { // force to scroll to button for lower fields
buttonViewRequester.bringIntoView()
} else {
bringIntoViewRequesters[viewItem].bringIntoView()
}
}
}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
.fillMaxSize()
.statusBarsPadding()
.navigationBarsPadding()
.imePadding()
.padding(10.dp)
.verticalScroll(rememberScrollState())
) {
repeat(6) { viewItem ->
Row(
modifier = Modifier
.bringIntoViewRequester(bringIntoViewRequesters[viewItem]),
) {
TextField(
value = "",
onValueChange = {},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(
onNext = { focusManager.moveFocus(FocusDirection.Down) }),
modifier = Modifier
.onFocusEvent { focusState ->
requestBringIntoView(focusState, viewItem)
},
)
}
}
Button(
onClick = {},
modifier = Modifier
.bringIntoViewRequester(buttonViewRequester)
) {
Text(text = "I'm Visible")
}
}
}
Try to google into such keywords: Modifier.statusBarsPadding(), systemBarsPadding(), navigationBarsPadding().
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
makeStatusBarTransparent()
//WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
Box(
Modifier
.background(Color.Blue)
.fillMaxSize()
.padding(top = 10.dp, bottom = 10.dp)
.statusBarsPadding() //systemBarsPadding
) {
//Box(Modifier.background(Color.Green).navigationBarsPadding()) {
Greeting("TopStart", Alignment.TopStart)
Greeting("BottomStart", Alignment.BottomStart)
Greeting("TopEnd", Alignment.TopEnd)
Greeting("BottomEnd", Alignment.BottomEnd)
//}
}
}
/* setContent {
MyComposeApp1Theme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = Color.Red) {
Box(Modifier
.fillMaxSize()
.padding(top = 34.dp)
) {
Greeting("Android")
}
}
}
}*/
}
}
#Composable
fun Greeting(name: String, contentAlignment: Alignment) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = contentAlignment
) {
Text(
text = "Hello $name!",
Modifier
.background(color = Color.Cyan)
)
}
}
#Preview(showBackground = true)
#Composable
fun DefaultPreview() {
MyComposeApp1Theme {
Greeting("Android", Alignment.TopStart)
}
}
#Suppress("DEPRECATION")
fun Activity.makeStatusBarTransparent() {
window.apply {
clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
statusBarColor = android.graphics.Color.GREEN//android.graphics.Color.TRANSPARENT
}
}
val Int.dp
get() = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
toFloat(),
Resources.getSystem().displayMetrics
)