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
  • y

    Yariv Ziporin

    01/02/2023, 4:28 PM
    Hi guys, what is the best way to share a view model between screens? I use navigation api for collecting data from multiple sign up forms. Should I use a single viewmodel for collecting the data or pass one when navigating from one form to another until I collect all the user input data?
    a
    c
    m
    • 4
    • 6
  • r

    robercoding

    01/02/2023, 5:23 PM
    Hi! Is there a way to listen for keyboard inputs when the keyboard has started the process of hiding? (Not when it's already hidden, it takes a bit of time) Or even better: Is there any way to intercept back handler when the keyboard is open? I see similar questions on SO have been asked but I don't see any answer 😅
    z
    e
    +2
    • 5
    • 11
  • t

    Travis Griggs

    01/02/2023, 7:01 PM
    I'm working my way through an Animation codelab, and a common one is to add .animateContentSize to Rows and Columns. What are the negatives to just doing this by default? I know with UIKit code, things just generally animate unless you need them not to. But the norm here, seems to be to have to turn a lot of animation on. Does it hurt to just turn these on by default, but turn them off when problematic?
    d
    • 2
    • 1
  • n

    nuhkoca

    01/02/2023, 7:47 PM
    Hello, I am returning a url in string format from my
    ViewModel
    in text click and subscribe the output in composable function as follows;
    val url by viewModel.output.url.subscribeAsState(initial = null)
    However, since the url is always the same string, only the first click opens browser, subsequent ones don’t do anything due to
    subscribeAsState
    How do I make this work properly for identical strings?
    z
    y
    • 3
    • 6
  • u

    ursus

    01/02/2023, 10:27 PM
    Is it normal for
    Image
    to be never skipped?
    Image(
        modifier = Modifier
            .size(48.dp)
            .padding(12.dp),
        painter = painterResource(id = R.drawable.ic_headphones),
        contentDescription = null,
    )
    I’m looking around in Layout monitor and I see this never skipped when ui is recomposed
    m
    e
    +3
    • 6
    • 22
  • r

    ritesh

    01/03/2023, 9:05 AM
    General preference is to always provide unique keys to the
    Lazy
    - What if i don't have a unique key for my model and i know that
    List<>
    data set positions won't be re-arranged but only new data-set will be appended, i can live without giving unique keys (without going into the path of generating some unique keys - like UUID for each item) to it i believe or there's a trade-off?
  • r

    Rafs

    01/03/2023, 9:53 AM
    I have a strange issue in my code where
    LaunchedEffect
    from my composable is getting called before
    onDispose
    of the destination navigation composable’s
    DisposableEffect
    j
    • 2
    • 1
  • b

    Brais Gabin

    01/03/2023, 11:09 AM
    Hello! I have a
    List<@Composable () -> Unit>
    . And I want to display it in a
    LazyColumn
    with a
    Space
    between each of them.
    LazyColumn {
      items(list) { composable ->
        composable.invoke()
        Space(height = 4.dp)
      }
    }
    The problem is that some of them can emit nothing to the tree. That means that visually I get double
    Space
    between some components. How would you avoid this problem? Those functions that emit nothing could start emitting at any point if their state change.
    j
    t
    • 3
    • 5
  • f

    FunkyMuse

    01/03/2023, 11:55 AM
    Hey guys, how would you handle
    android.intent.action.SEND
    With compose navigation component? I want to open a nested navigation destination that accepts a uri which is basically a string encoded when passing the argument and decoding when reading it
    • 1
    • 2
  • k

    KotlinLeaner

    01/03/2023, 12:09 PM
    Hi, I want to make a list of unique items in my list in jetpack compose. So I am trying to use MutableSet in my project. I know that mutableStateListOf is using for list in jetpack compose. I have another reason to use of mutableStateListOf in my project. So is there is way we can use of
    MutableSet
    with
    mutableStateListOf
    ?
    val list by lazy { mutableStateListOf<ScanResult>() }
    Many Thanks
    z
    • 2
    • 4
  • d

    dorche

    01/03/2023, 2:50 PM
    Hi this could go in a few channels but I am hoping for a Compose first solution here.. What’s the Compose way to handle a deep-link and keep your app/backstack state (ideally?) ? Looks like handleDeepLink clears the backStack one way or another so let’s say you have an an app that let’s the user make payments: • midway through using the app, the user goes to the payment flow which launches a Custom Chrome Tab (as per guidelines). • Payment Completed in Chrome Custom Tab. Deeplink issued to get back in the app. • Deeplink received and handled by the system
    handleDeepLink
    , back stack seems gone so now the when the user presses back after the payment flow confusingly that closes the app.
    c
    • 2
    • 3
  • h

    Hasan Nagizade

    01/03/2023, 4:45 PM
    val focusManager = LocalFocusManager.current
    focusManager.clearFocus()
    this code removes the focus from
    InputField
    and closes the keyboard. How can I close the keyboard but keep focus on
    InputField
    ?
    k
    r
    • 3
    • 2
  • n

    Norbi

    01/03/2023, 8:11 PM
    How can I check which Kotlin version is supported by a specific Compose/MP version, eg. v1.3.0-beta04-dev903? Thanks.
    j
    • 2
    • 4
  • r

    Rick Regan

    01/03/2023, 8:26 PM
    I’m trying to understand why this use of
    Crossfade
    is leaking its state holder. I have a Slider that I can interact with normally (no crossfades) but that will crossfade to its default value when a “reset” Button is pressed. I do this using a MutableState within a MutableState, the outer one being the target for Crossfade, and the inner one being the slider value (code in 🧵.) In the heap dump (after forcing garbage collection) I can see that the number of allocated SliderStateHolder/SliderState objects increases with each reset. Inasmuch as I understand heap dumps, the references look like they’re coming from “SnapshotStateList”, which would seem to indicate Compose continues to track the old states. I’d like to understand why (and what I could do to prevent it). Thanks.
    d
    • 2
    • 9
  • j

    John O'Reilly

    01/03/2023, 10:21 PM
    Dev version (1.4.0-dev-k1.8.0-33c0ad36f83) of Compose Compiler now available for Kotlin 1.8.0 https://androidx.dev/storage/compose-compiler/repository
  • a

    Aaron Waller

    01/04/2023, 7:25 AM
    I want to hide a post from my list by clicking a button inside my BottomSheet Layout. My ModalBottomSheetLayout is outside the Scaffold to have it above my BottomAppBar. I’m using the BottomSheet as a options menu for my Post items. Now I need to Hide a post whenever someone clicks on “Hide” inside the BototmSheet. How can I do that now? (code in thread)
    f
    d
    • 3
    • 28
  • s

    Shakil Karim

    01/04/2023, 10:42 AM
    Hi, i'm trying to use Adam Powelhttps://gist.github.com/adamp/17b4e5cfafc7d44a0023dc2fbdb972e8
  • s

    Shakil Karim

    01/04/2023, 10:47 AM
    Hi, i'm trying to this BackStack implementation from Adam Powell's Gist, but when i use ViewModel with each route it's giving me this exception what could be reason for this ? giving me IllegalArgumentException SavedStateProvider with the given key is already registered
    • 1
    • 2
  • e

    elye

    01/04/2023, 11:26 AM
    I have a simple Todo Compose View as
    class AppViewModel : ViewModel() {
        private var todoList = listOf(
            TodoItem(0, "My First Task"),
            TodoItem(1, "My Second Task", true)
        )
        private val _todoListFlow = MutableStateFlow(todoList)
    
        val todoListFlow: StateFlow<List<TodoItem>> get() = _todoListFlow
    
        fun setUrgent(index: Int, value: Boolean) {
            val modified = todoList.toMutableList()
            modified[index] = modified[index].copy(urgent = value)
            todoList = modified
            _todoListFlow.value = modified
        }
    }
    
    val viewModel = AppViewModel()
    
    @Composable
    fun MyTodoList {
        val todoListState = viewModel.todoListFlow.collectAsState()
    
       LazyColumn(modifier = Modifier.fillMaxHeight()) {
            items(items = todoListState.value, itemContent = { item ->
                Row {
                    Text(text = item.title)
                    Checkbox(
                        checked = item.urgent,
                        onCheckedChange = {
                            val index = todoListState.value.indexOf(item)
                            viewModel.setUrgent(index, it)
                        }
                    )
                }
            })
        }
    }
    But I dislike to update a field in the list, I have to create a modify list to pass to the stateFlow.
    fun setUrgent(index: Int, value: Boolean) {
            val modified = todoList.toMutableList()
            modified[index] = modified[index].copy(urgent = value)
            todoList = modified
            _todoListFlow.value = modified
        }
    I can fix it using Solution in https://stackoverflow.com/a/75004437/3286489, but feel it is wrong, as that solution is having MutableState in ViewModel. I wonder how can I avoid the need to create the entire list to send through the StateFlow, if I just need to change a variable that update the compose view?
    z
    m
    • 3
    • 2
  • o

    oday

    01/04/2023, 12:00 PM
    where do you store test tags? like I have some tags here in a class that constructs some composables, and I’ve defined them like this:
    object TestTags {
        const val eventsListTag = "Events List"
        const val errorPromptTag = "Error Prompt"
        const val emptyPromptTag = "Empty Prompt"
    }
    how do you do this?
    d
    • 2
    • 2
  • h

    Hasan Nagizade

    01/04/2023, 12:37 PM
    why
    onFocusChanged
    is not getting triggered every time user clicks on
    InputField
    ? how to make
    InputField
    get focus every time user clicks on it?
    z
    a
    z
    • 4
    • 5
  • e

    elye

    01/04/2023, 1:05 PM
    Should we store "_mutableStateListOf_" in ViewModel or in the Compose Function? If we have it in the Compose Function, looks like we'll need to create a new list for every modification of it, as explain here https://kotlinlang.slack.com/archives/CJLTWPH7S/p1672831604690449. So tempting to put "_mutableStateListOf"_ in the ViewModel, but feel it is wrong.
    z
    • 2
    • 1
  • m

    myanmarking

    01/04/2023, 1:33 PM
    I can’t wrap my head about this one issue. Why would this code do not run the layout inner lambda ?
    z
    l
    • 3
    • 12
  • e

    Elio Maroun

    01/04/2023, 2:55 PM
    Should I use a different floating action button for every screen or use the one in scaffold?
  • a

    AloneWalker

    01/04/2023, 3:17 PM
    I have this code with stateIn, my questions are: 1. Am I using it correctly? 1. Is it better to do this instead of collecting the flow from ViewModel? 2. I have read we shouldn't use methods with statIn, what can I do if I need to pass parameters? any example? Repository: override val appLanguageStream: Flow<String> = dataStore.data.map { preferences -> val preferencesKey = stringPreferencesKey(Constants.APP_LANGUAGE) preferences[preferencesKey] ?: Constants.DEFAULT_LANGUAGE } ViewModel: val appLanguageStream: StateFlow<Resource<String>> = settingsRepository.appLanguageStream.asResource().stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), Resource.Success(Constants.DEFAULT_LANGUAGE) ) Screen: val appLanguageStream by viewModel.appLanguageStream.collectAsStateWithLifecycle() LaunchedEffect(key1 = appLanguageStream){ // update ViewModel uiState }
  • i

    iroyo

    01/04/2023, 4:16 PM
    Hi! I’m using coil to load images in compose and I need to send as a query-param with the width of the composable. Right now the only way I’ve found is using
    onGloballyPositioned
    on the
    Image
    modifier to get the size and then set a global variable of an Interceptor.. What I have is something like:
    Image(
        painter = painter,
        modifier = modifier.onGloballyPositioned {
            coilInterceptor.config.params[PARAM_WIDTH] = it.size.width.toString() 
        },
    where: coilInterceptor is a singleton Interceptor…. I’m trying to avoid this. I much rather prefer passing to the
    ImageRequest
    directly the url with the size concatenated
    z
    a
    • 3
    • 7
  • l

    Landry Norris

    01/04/2023, 6:00 PM
    I’m trying to build a compose layout that depends on orientation. I have the following code, but it never responds properly to the first orientation change (The collect never runs). I rotate my phone from portrait to landscape, and the value of orientation is still ORIENTATION_PORTRAIT. Rotating back to portrait and back to landscape works, though. What am I doing wrong here?
    var orientation by remember { mutableStateOf(Configuration.ORIENTATION_PORTRAIT) }
    val config = LocalConfiguration.current
    
    LaunchedEffect(config) {
        // Save any changes to the orientation value on the configuration object
        snapshotFlow { config.orientation }
            .collect { orientation = it }
    }
    a
    • 2
    • 19
  • a

    Andy Himberger

    01/04/2023, 8:09 PM
    Is there a way to track accessibility focus (where the talkback highlight is)? I have added onFocusEvent/onFocusChanged + focusable modifiers, and I don't get any events when navigating with talkback. I DO get notifications when navigating with the keyboard or when i use a focusRequester to request focus. I've run into wanting this a couple times where I'm trying to keep accessibility focus staying on the same item when re-creating the activity on rotation, or right now where I have custom accessibility actions to reorder items in a list (since the default 'drag reorder' is not going to be good for accessible users, the actions give another way to do it), and it seems like when an item is moved focus should stay on that item. The timing of that is not straightforward though since the talkback custom actions dialog itself has focus for awhile, and you can't move focus until after it has restored focus into the compose view, but I haven't found a way to listen for when that happens. -- I can guess and run a delayed coroutine so it moves slightly after, that seems kind of jumpy
  • z

    Zach Klippenstein (he/him) [MOD]

    01/04/2023, 9:30 PM
    I’m not sure i see a question there…
  • a

    alp

    01/04/2023, 11:18 PM
    Does anybody know whether LazyColumn can be used inside
    androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    ? There are examples here with a fix using
    Modifier.nestedScroll(rememberNestedScrollInteropConnection())
    for bottom sheet but it seems like it doesn’t work with hierarchy like:
    <SwipeRefreshLayout>
       <ComposeView>
    </SwipeRefreshLayout>
    scrolling up immediately triggers the swipe refresh.
    e
    • 2
    • 13
Powered by Linen
Title
a

alp

01/04/2023, 11:18 PM
Does anybody know whether LazyColumn can be used inside
androidx.swiperefreshlayout.widget.SwipeRefreshLayout
? There are examples here with a fix using
Modifier.nestedScroll(rememberNestedScrollInteropConnection())
for bottom sheet but it seems like it doesn’t work with hierarchy like:
<SwipeRefreshLayout>
   <ComposeView>
</SwipeRefreshLayout>
scrolling up immediately triggers the swipe refresh.
e

ephemient

01/04/2023, 11:28 PM
https://android-developers.googleblog.com/2022/05/whats-new-in-jetpack-compose.html#:~:text=rememberNestedScrollInteropConnection (
SwipeRefreshLayout
is a
NestedScrollingParent3
like
CoordinatorLayout
)
val state = rememberLazyListState()
LaunchedEffect(listState) {
    swipeRefreshLayout.setOnChildScrollUpCallback { _, _ -> listState.firstVisibleItemScrollOffset > 0 }
}
LazyColumn(state = state, ...)
a

alp

01/05/2023, 12:35 AM
First of all, thanks for the code snippet - that works for the sample but do you know why it doesn’t work out of the box similar to other
NestedScrollingParent3
ViewGroups
CoordinatorLayout
for example? In more real-world complex scenario, such as when compose code is encapsulated within a fragment, there is not way to propagate
SwipeRefreshLayout
reference to the compose code, as far as I understand,
NestedScrollingParent3
abstraction should solve this issue
e

ephemient

01/05/2023, 1:45 AM
there's multiple different things happening here
SwipeRefreshLayout
is a
NestedScrollingParent3
, but
ComposeView
is not a
NestedScrollingChild3
a

alp

01/05/2023, 1:50 AM
I thought that
NestedScrollInteropConnection
makes it a
NestedScrollingChild3
e

ephemient

01/05/2023, 1:54 AM
ah, yeah. I tracked it down to the wrong place
ComposeView
is returning false from
canScrollVertically
before a gesture starts, it seems
so
SwipeRefreshLayout
doesn't delegate a pull down into
ComposeView
, but if you pull even a little bit first then it all works
a

alp

01/05/2023, 1:57 AM
I haven’t debugged it much, just saw that once I scrolled to the bottom, interop connection doesn’t receive events
as if SwipeToRefresh consume it
e

ephemient

01/05/2023, 1:59 AM
TBH I'm not entirely sure why it doesn't work on the Compose side…
a

alp

01/05/2023, 1:59 AM
me too, but thanks for looking into it
View count: 14