https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
compose
  • t

    tylerwilson

    10/22/2021, 1:50 PM
    Working on a Compose layout, and using Box. But I need to align with the screen size, so I tried BoxWithContraint. But when I use that, it appears to be in a constant update loop (Box does not do this), which kills performance. Any tips on how to perhaps speed this up, or get the screen width for the plain old Box?
    c
    3 replies · 2 participants
  • r

    Rak

    10/22/2021, 2:31 PM
    Hi, can anyone recommend. good sample project (or real one) that uses Compose? I am particularly interested in how the composables are held in various packages and files along with examples of unit testing.
    a
    s
    +1
    3 replies · 4 participants
  • a

    Ahmet Hasim Delibas

    10/22/2021, 2:36 PM
    I have scroll state with rememberScrollableState(), used in Column:
    c
    2 replies · 2 participants
  • c

    Chris Fillmore

    10/22/2021, 3:27 PM
    Is there a recommendation on how to implement filtering in a
    LazyColumn
    ?
    7 replies · 1 participant
  • n

    Nick

    10/22/2021, 4:16 PM
    Is there anything wrong with getting the value of a state right away and consuming throughout the composable tree?
    val buttonStateValue = myViewModel.buttonState.collectAsState().value
    MyScreen(buttonStateValue)
    
    ....MyScreen consumes the buttonStateValue, and passes it down to a bunch of other composables
    c
    2 replies · 2 participants
  • a

    Afzal Najam

    10/22/2021, 5:50 PM
    Weird that all
    Composables
    are PascalCase except some, like
    updateTransition
    , which is camelCase.
    j
    6 replies · 2 participants
  • m

    mattinger

    10/22/2021, 7:37 PM
    Quick question. I’m assuming (much like with earlier versions), that compose 1.0.4 only requires 1.5.31 of kotlin at compile time (and not runtime)?
    :yes: 1
    👍 1
    b
    1 reply · 2 participants
  • m

    Mehdi Haghgoo

    10/22/2021, 8:18 PM
    I am having a hard time understanding the rationale behind using Accompanist for Compose Navigation animation. As I understand from @Ian Lake’s article on Medium, navigation animation APIs are not yet stable in Compose, so we cannot use them directly, because they will break out code. On the other hand, when we use Accompanist navigation animations, they are also annotated with ExperimentalAnimationApi. So, kind of confused, we are using experimental animations anyway, why bother using them through another library like Accompanist?
    i
    7 replies · 2 participants
  • c

    Clament John

    10/23/2021, 5:22 AM
    [Answered] How to pop back to previous activity in Jetpack navigation?
    i
    3 replies · 2 participants
  • a

    Android75

    10/23/2021, 9:15 AM
    i am new in Compose, how can i improve ? i saw some google tutorial.. but they are for simple UI
    a
    2 replies · 2 participants
  • i

    Ink

    10/23/2021, 7:07 PM
    How I can align center vertically my text?
    v
    3 replies · 2 participants
  • i

    Ink

    10/23/2021, 10:33 PM
    Is it possible to set padding to 0 for inside text?
    1 reply · 1 participant
  • c

    Colton Idle

    10/24/2021, 5:07 AM
    This is currently how I'm showing a snackbar.
    if (viewModel.state.snackBarMessage.isNotEmpty()) {
        coroutineScope.launch {
            scaffoldState.snackbarHostState.showSnackbar(viewModel.state.snackBarMessage)
            viewModel.state.snackBarMessage = ""
        }
    }
    I get hit with a lint warning though.
    Calls to async or launch should happen inside a LaunchedEffect and not composition
    Can anyone point me in the right direction over the fix? Changing the
    if
    with
    LaunchedEffect
    makes the lint error go away, but I'm not sure if that's "right"/idiomatic compose here.
    a
    8 replies · 2 participants
  • a

    Android75

    10/24/2021, 3:02 PM
    g
    z
    3 replies · 3 participants
  • a

    Android75

    10/24/2021, 3:02 PM
    i don’t know why delegate doesn’t work
    h
    4 replies · 2 participants
  • i

    itnoles

    10/25/2021, 4:45 AM
    https://chris.banes.dev/always-provide-a-modifier/ Would there be a lint warning for something like this?
    ☝️🏼 1
    🙏🏼 1
    🙏 5
    ☝️ 2
    👀 6
    ➕ 2
    c
    d
    2 replies · 3 participants
  • k

    kierans777

    10/25/2021, 6:20 AM
    I'm wanting to use an ExpansionPanel (https://material.io/archive/guidelines/components/expansion-panels.html) in Compose. However I can't seem to find the right function. Can anyone help me please?
    s
    1 reply · 2 participants
  • d

    darkmoon_uk

    10/25/2021, 7:41 AM
    Does anyone have any clues when Compose
    1.1.0
    will hit
    beta
    ? It's been on
    alpha06
    for some time (see Google Maven repo). It has critical fixes we need to adopt regarding back button behaviour, and
    beta
    status is significant for us.
    👀 2
    t
    a
    +1
    5 replies · 4 participants
  • m

    Michal Klimczak

    10/25/2021, 8:51 AM
    So I did this and I hate it. How do you properly return results from one nav destination to another when popping back?
    /**
     * Observes the callback result from previous NavController backStackEntry and makes sure,
     * that it's cleared so the LiveData doesn't trigger again (by default it triggers with the old value
     * for every resubscription)
     *
     * Ref: <https://developer.android.com/guide/navigation/navigation-programmatic#returning_a_result>
     */
    fun <T> NavController.navigationCallbackFlow(argKey: String) = this
        .currentBackStackEntry!!
        .savedStateHandle
        .getLiveData<T>(argKey)
        .asFlow()
        .map { this.currentBackStackEntry!!.savedStateHandle.get<T>(argKey) }
        .onEach { this.currentBackStackEntry!!.savedStateHandle.remove<T>(argKey) }
        .filterNotNull()
    t
    i
    +1
    32 replies · 4 participants
  • i

    Ink

    10/25/2021, 9:20 AM
    Hi guys, How can I decrease padding inside the button? I want to have text closer to button border
    r
    3 replies · 2 participants
  • s

    Sergey Y.

    10/25/2021, 9:41 AM
    While browsing CLs, I noticed this one about documentation updates, which is good. However, inside the code on
    line 157
    , I saw the comment
    "Don't do this."
    But why? I know that
    .onSizeChanged
    will only fire after the first composition, and we have to wait to get the required attribute. This seems acceptable to me. What other ways can we get the attributes of the child layout besides writing a custom layout using
    Layout
    composable or
    Modifier.layout
    ? https://android-review.googlesource.com/c/platform/frameworks/support/+/1856275/7/compose/in[…]va/androidx/compose/integration/docs/phases/Phases.kt
    a
    a
    6 replies · 3 participants
  • b

    bodo

    10/25/2021, 10:03 AM
    Hi guys. I am searching for a way to write a custom modifier, which scales the font size if the composable has a specific size (width)
    Text("This is a test", modifier = Modifier.dynamicTextSize(14.sp))
    • composable width <=100dp it should use the specified 14.sp • composable width > 100dp it should use the specified 14.sp multiplied with a scale factor -> e.g. scalefactor = 1.5 * 14.sp = 21.sp Can you please show me how to achieve this best? Thx
    l
    a
    4 replies · 3 participants
  • j

    jannis

    10/25/2021, 10:23 AM
    I have a
    TextField
    with a
    TextFieldValue
    . When I select a Text the
    onValueChange
    callback is invoked correctly. However when I perform a configuration change the `onValueChange`callback is invoked again (before the recomposition is invoked). This time with wrong values. The selection is cleared. When I use a
    remembersaveable
    it works more or less. It seems the selection is restored with the correct values (even though the context menu on the text is missing). It seems it simply doesn't update it before the recomposition. Since my state is more complex I store the value in my
    ViewModel
    . Of course the value get's updated with the wrong state before the recomposition. Any ideas how to solve this? Or is it a bug?
    a
    s
    7 replies · 3 participants
  • a

    Arpit Shukla

    10/25/2021, 10:46 AM
    How to set a progress listener to compose animations? I am trying to use
    animateFloatAsState
    , I see that it accepts a
    finishedListener
    but how to provide something like an
    updateListener
    ?
    m
    12 replies · 2 participants
  • i

    Ink

    10/25/2021, 12:57 PM
    I use
    HorizontalPager
    and I want to make second item visible. I"ve added itemSpacing but it doesn't work, any idea?
    HorizontalPager(state = pagerState, itemSpacing = 35.dp) {
        HorizontalViewPagerItem()
    }
    😒olved: 1
    l
    4 replies · 2 participants
  • m

    mattinger

    10/25/2021, 2:42 PM
    Looking for an approach to trigger an event in a lazy column when a card is scrolled into view. At the moment, i am using a LaunchedEffect (though suspect SideEffect would be enough). Let’s for now at least assume the composition doesn’t change over time, just scrolls on and off screen. I’m wondering if this is the right approach (see thread for code)
    a
    e
    14 replies · 3 participants
  • a

    alorma

    10/25/2021, 3:00 PM
    Hi! Is this the best way to get
    onStart
    events in compose? Code in 🧵
    m
    a
    +1
    18 replies · 4 participants
  • b

    Bradleycorn

    10/25/2021, 3:46 PM
    I’m working with a
    Row
    that renders itself like the image here. In the Row, the red/blue box should fill the height of the row, but also not affect the measured height. Meaning, the other content should determine the height of the row, and then the red/blue box should fill that height. I was using
    InstrinsicSize.Min
    to accomplish this. But alas, the row content has gotten complex enough that I need to use a
    SubComposeLayout
    in it (a
    BoxWithConstraints
    ), and well, Intrinsics and SubComposeLayout don’t play nice together. I had been working on this before, and @Zach Klippenstein (he/him) [MOD] had helped me in another thread (https://kotlinlang.slack.com/archives/CJLTWPH7S/p1621712795136000), suggesting that I use a Custom Layout for the Row composable. I’m finally getting a chance to work on that. The code I’ve come up with as a starting point for my custom Layout is included in this thread. I was hoping to get some feedback to see if I’m on the right track with it, since it’s my first attempt at a custom layout….
    z
    10 replies · 2 participants
  • c

    Chris Johnson

    10/25/2021, 3:54 PM
    Is there a reason
    Modifier.offset
    causes recomposition infinitely when I'm not touching the screen? I'm using it together with
    animateIntOffset
    + user scroll. Code in 🧵
    d
    g
    22 replies · 3 participants
  • t

    Tolriq

    10/25/2021, 6:46 PM
    Since LazyVerticalGrid does not support span for headers I'm trying to use a LazyColumn with Grid and windowed on the list. Since I need fixed counts the elements have all weight(1f) and aspectRatio() for some part of the content but performance is not great at all. Is there something more efficient than the weight or anything I can do to hint the LazyColumn that all rows will have the same height to improve perf?
    a
    13 replies · 2 participants
Powered by Linen
Title
t

Tolriq

10/25/2021, 6:46 PM
Since LazyVerticalGrid does not support span for headers I'm trying to use a LazyColumn with Grid and windowed on the list. Since I need fixed counts the elements have all weight(1f) and aspectRatio() for some part of the content but performance is not great at all. Is there something more efficient than the weight or anything I can do to hint the LazyColumn that all rows will have the same height to improve perf?
a

Andrey Kulikov

10/25/2021, 7:13 PM
LazyVerticalGrid internally using LazyColumn with Rows with weight on elements and we don’t see any performance issues. Could you please clarify why do you think weight is affecting the performance?
t

Tolriq

10/25/2021, 7:30 PM
Completely random guess from profiler and previous experience, when you see large measure part. Don't really know how to properly analyse the compose part, was actually simpler in view world.
a

Andrey Kulikov

10/25/2021, 7:52 PM
most likely the issue is that you need to do recompositions on every scroll offset. can you please show the code?
t

Tolriq

10/25/2021, 7:58 PM
I made tons of different test but here's one version:
val items = remember(lazyPagingItems.itemCount) {
                            derivedStateOf {
                                List(lazyPagingItems.itemCount) { it }.windowed(stepSize, stepSize, true)
                            }
                        }
						
						
LazyColumn(
	state = lazyListState,
	contentPadding = PaddingValues(vertical = 8.dp),
	content = {
		item {
			Header(viewModel)
		}
		items(items.value) { items ->
			Row(
				modifier = Modifier
					.fillMaxWidth()
					.padding(horizontal = 4.dp)
			) {
				items.map { lazyPagingItems[it] }.forEach {
					AlbumEntryGrid(it, viewModel.getThumbnailImagePath(it)) {
						if (it != null) {
							navigator.navigateTo(AlbumDetailsScreenDestination(it))
						}
					}
				}
				repeat(stepSize - items.size) {
					Spacer(modifier = Modifier.weight(1f))
				}
			}
		}
	}
)						
								
@Composable
fun RowScope.AlbumEntryGrid(mediaItem: MediaItem?, thumbnailImagePath: ImagePath, onRowClick: () -> Unit) {
    val finalMediaItem = mediaItem ?: MediaItem(title = "Placeholder")
    Box(
        Modifier
            .clickable { onRowClick() }
            .aspectRatio(1f)
            .weight(1f)
            .padding(4.dp)
            .clip(RoundedCornerShape(8.dp)),
    ) {
        val imageRequest = ImageRequest(
            thumbnailImagePath,
            exactSize = false,
            debugTag = "AlbumEntryGrid"
        )
        Image(
            imageRequestPainter = rememberImageRequestPainter(imageRequest = imageRequest),
            contentDescription = null,
            error = @Composable { Error(finalMediaItem) },
            placeHolder = @Composable { SurfacePlaceHolder() },
            contentScale = ContentScale.FillBounds,
            modifier = Modifier
                .aspectRatio(1f)
        )
    }
}
Logging composition count I do not see extra composition ocurring. 1 time the lazyColum and 3 times each item for the 3 image states. Only thing that is strange is that despite the itemcount not changing.
remember(lazyPagingItems.itemCount) {
                            derivedStateOf {
                                List(lazyPagingItems.itemCount) { it }.windowed(stepSize, stepSize, true)
                            }
                        }
Is triggering a recalculation of the derived state and so the tree when compose paging load a new page. (But the perf issue is also ocutring when all pages are loaded so it's not the root cause). Is there something wrong with that approach to have a stable state that contains a list of number that must only be recreated when the actual itemcount change ?
a

Andrey Kulikov

10/25/2021, 8:18 PM
do you use lazyListState somewhere else? not in the code you already shared
t

Tolriq

10/25/2021, 8:23 PM
Nope a simple
val lazyListState = rememberLazyListState()
It's just defined earlier as I use the same when switching from list to grid
But as said I'm using :
@Composable
inline fun LogCompositions(tag: String) {
    if (ENABLE_DEBUG_COMPOSITION_LOGS && BuildConfig.DEBUG) {
        val ref = remember { Ref(0) }
        SideEffect {
            ref.value++
            Logger.logger.logError(tag, "Compositions: ${ref.value}", null, true)
        }
    }
}
To check on extra composition and each item is only composed 3 times as the image state goes from empty to loading to success / error
Anyway it's very late here, but thanks for confirming that the row + weight should work and I need to try to figure out where the issue is, but it's not a wrong approach to my problem.
@Andrey Kulikov After doing some tests this seems like a regression from Compose 1.1
val items = List(14000) { listOf(it, it, it) }
                LazyColumn(
                    state = rememberLazyListState(),
                    content = {
                        items(items) { items ->
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(4.dp)
                                    .background(Color.Red)
                            ) {
                                items.forEach {
                                    Surface(
                                        color = Color.DarkGray,
                                        modifier = Modifier
                                            .clickable { /*onRowClick()*/ }
                                            .weight(1f)
                                            .aspectRatio(5f)
                                            .padding(4.dp)) {}
                                }
                            }
                        }
                    }
                )
This in a new default compose activity just updated to compose 1.1 will be insanely slow
HWUI overlay looks like this for this simple when scrolling.
View count: 4