https://kotlinlang.org logo
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
  • g

    Gauthier POULET

    09/01/2020, 2:17 PM
    Hi, I found an error on 1) Introduction page on the code lab “Layouts in Jetpack Compose” I think in the image, Column and Row are reversed (nothing serious).
    m
    • 2
    • 16
  • j

    JD

    09/01/2020, 2:18 PM
    Are there plans in future to enhance the scaffold API so that it takes into account various cutouts while going edge-to-edge layouts? Trying on a pixel 4A emulator the camera is positioned such that it overlaps the drawer or the place the title would be present.
    m
    a
    m
    • 4
    • 8
  • j

    jaqxues

    09/01/2020, 2:51 PM
    i suppose there is no way to get a nice ViewPager experience? where you can swipe from one tab to another?
    m
    a
    • 3
    • 4
  • h

    harry248

    09/01/2020, 3:02 PM
    Anyone else having problems using a ComposeView while enabling minifcation (R8/Proguard)? I am getting the following exception (see thread):
    a
    a
    +4
    • 7
    • 12
  • s

    Slackbot

    09/01/2020, 4:45 PM
    This message was deleted.
    s
    y
    • 3
    • 10
  • m

    Mehdi Haghgoo

    09/01/2020, 4:51 PM
    Do we have stateful Composables as compared to Stateful and Stateless Widgets in Flutter?
    s
    l
    • 3
    • 6
  • z

    zak.taccardi

    09/01/2020, 5:26 PM
    flow.collectAsState("initialState")
    requires an initial state (when not using a
    StateFlow<T>
    . How can we avoid having this initial state? For example, I would like to have a composable not be considered “ready” until the
    Flow<T>
    emits. By ready, I mean shown to the user. Is something like this possible? The idea would be something like
    fragment.postponeEnterTransition(..)
    (link) which allows the
    Fragment
    to asynchronously load its data before appearing to the user. This way an initial state would not need to be provided and only fully loaded data need be displayed
    👍 4
    d
    a
    +3
    • 6
    • 36
  • d

    dimsuz

    09/01/2020, 5:56 PM
    Why is this not working? No text appears in the input field
    val inputState: TextFieldValue by mutableStateOf(TextFieldValue())
    TextField(value = inputState.value, onValueChange = { inputState = it })
    But if I wrap in
    remember
    than text input starts working. I am asking because Compose State codelab has examples which have only
    by mutableStateOf
    and no
    remember
    (for example in ViewModel section), but TextField turns out to be special here?
    f
    z
    • 3
    • 4
  • j

    JD

    09/01/2020, 6:16 PM
    Using scaffold API if we use a drawer. is it expected that the drawer would be opened when scrolled from midway in the screen? Example Video: I have enabled the screen taps to showcase where the drag was being made from. Is this expected behavior. I understand that now since the edge of the screen is used for gesture navigation however if the drawer opens from anywhere wouldn't it be a wrong behavior? Note: Pasting code in comments
    scaffoldAPIDrawer.mp4
    m
    • 2
    • 2
  • c

    carbaj0

    09/01/2020, 6:20 PM
    Random exception
    a
    g
    • 3
    • 5
  • s

    Sergey Y.

    09/01/2020, 8:30 PM
    Is there any way to make the clickable region larger than the icon without making the icon size bigger? I want to achieve a borderless ripple effect and easier clicking. Maybe some modifier? Is there an analogy to the 
    selectableItemBackgroundBorderless
     attribute? Thanks.
    f
    j
    +4
    • 7
    • 24
  • m

    Michał Jurczyk

    09/01/2020, 9:08 PM
    Hey 👋 Does Compose support drag and drop? I have a
    LazyColumn
    of cards and want to drag'n'drop items onto the cards from a picker. In native UI I used to do it with
    setOnDragListener
    listening to
    ACTION_DROP
    and
    clipData
    🤔
    z
    • 2
    • 7
  • s

    Siyamed

    09/01/2020, 10:55 PM
    hard to read
    g
    • 2
    • 20
  • m

    Mehdi Haghgoo

    09/02/2020, 4:07 AM
    No matter how much padding I add, the floating action button does not seem to give good padding to the text inside it (in Preview).
    j
    • 2
    • 1
  • f

    fengdai

    09/02/2020, 4:19 AM
    When Compose recomposes based on new inputs, it only calls the functions or lambdas that might have changed, and skips the rest.
    Why is the root Compose function
    RecompositionBehavior
    always recomposed while the
    Switch
    only changes the input of
    MaterialTheme
    ?
    @Preview("RecompositionBehavior")
    @Composable
    fun RecompositionBehavior() {
        Log.d("Recompose", "RecompositionBehavior")
        var darkTheme by remember { mutableStateOf(false) }
        MaterialTheme(
            colors = if (darkTheme) darkColors else lightColors,
        ) {
            Log.d("Recompose", "MaterialTheme")
            Surface {
                Switch(checked = darkTheme, onCheckedChange = { darkTheme = it })
            }
        }
    }
    s
    • 2
    • 2
  • m

    Mehdi Haghgoo

    09/02/2020, 8:46 AM
    private val todoViewModel by viewModels<TodoViewModel>()
    Why can't we just write
    val todoViewModel = List<TodoViewModel>()
    ?
    j
    • 2
    • 4
  • s

    Spikey Sanju

    09/02/2020, 11:19 AM
    How to call lifecycleScope inside a composable function?
    m
    z
    t
    • 4
    • 8
  • t

    Timo Drick

    09/02/2020, 11:47 AM
    I try to get SavedInstanceState working in my custom Navigation framework. I am able to save state when dispose one screen and i will create a new UiSavedStateRegistry with restored values and provide it to the child composable. Unfortunatly the child composable with a
    var checkBoxState by savedInstanceState { false }
    Is not using the provided Registry :-(
    log("${item.data} saved state: $${item.savedState}")
        val restoredRegistry by remember(item.savedState) {
            log("${item.data} Create new registry with: ${item.savedState}")
            mutableStateOf(UiSavedStateRegistry(restoredValues = item.savedState, canBeSaved = { true }))
        }
        Providers(UiSavedStateRegistryAmbient provides restoredRegistry) {
            log("${item.data} ${UiSavedStateRegistryAmbient.current}")
            children(item.data)
            onDispose {
                val saved = restoredRegistry.performSave()
                log("${item.data} onDispose saved: $saved")
                item.savedState = saved
            }
        }
    Maybe someone can point me into the right direction what is wrong?
    z
    • 2
    • 37
  • d

    Daniele B

    09/02/2020, 11:53 AM
    I am trying to implement a very simple Master/Detail app in Compose, where the Master screen is showing a list of items and the Detail screen is showing the details of the selected item. I am using a MultiPlatform ViewModel, where I would like to keep the state of which is the current screen that is shown. I am considering using just 1 Activity for the whole app. In order to manage the navigation I also need to listen to the BackButton. Can you please suggest what is the recommend way in Compose to get the BackButton event? Would it be the
    onBackPressed(){...}
    method of the Activity without calling
    super.onBackPressed()
    ?
    👍 1
    s
    f
    • 3
    • 9
  • z

    Zach Klippenstein (he/him) [MOD]

    09/02/2020, 12:07 PM
    I can't find any links on the page to report documentation bugs, but shouldn't
    dataExample
    use property delegation here? It looks like it's being used as though it is the actual value of the state. Also, the link to
    observeAsState
    is broken. Should these be reported on the issue tracker? https://developer.android.com/jetpack/compose/interop#async
    m
    • 2
    • 6
  • j

    jaqxues

    09/02/2020, 12:23 PM
    I am using a Switch, and adding Padding to the Modifier doesnt increase the clickable, swipeable area . The Switch is unusable with its Hitbox being this small Is there any way I can increase it with a Modifier or any other way?
    t
    z
    m
    • 4
    • 30
  • k

    Ketan

    09/02/2020, 12:48 PM
    Is it possible to add condition clause [lets say
    buildWhen (previousState, currentState)
    ] while re-composing the ui widget so if data is not changed for particular child ui widget it won’t be re-composed? Is there any way to achieve this?
    z
    • 2
    • 3
  • m

    Mehdi Haghgoo

    09/02/2020, 1:20 PM
    A value computed by
    remember
    will be stored in the composition tree, and only be recomputed if the keys to
    remember
    change. -link
    What is a key?
    m
    • 2
    • 3
  • m

    Mehdi Haghgoo

    09/02/2020, 1:52 PM
    The following code has some problem that causes the FAB to be located at the bottom-left of screen when app runs and once a new item is added to the lazy list, it jumps to the bottom-center.
    @Composable
    fun TodoScreen(
        items: List<TodoItem>,
        onAddItem: (TodoItem) -> Unit,
        onRemoveItem: (TodoItem) -> Unit
    ) {
        Column {
            LazyColumnFor(
                items = items,
                modifier = Modifier.weight(1f),
                contentPadding = InnerPadding(top = 8.dp)
            ) { todo ->
                TodoRow(
                    todo = todo,
                    onItemClicked = { onRemoveItem(it) },
                    modifier = Modifier.fillParentMaxWidth()
                )
            }
    
            // For quick testing, a random item generator button
            FloatingActionButton(
                    shape = CircleShape,
                    elevation = 8.dp,
                    icon = {
                        Row(modifier = Modifier.padding(16.dp)){
                            Icon(asset = vectorResource(id = R.drawable.add))
                            Text("Add New Item")
                        }
                             },
                    onClick = { onAddItem(generateRandomTodoItem()) },
                    modifier = Modifier.gravity(Alignment.CenterHorizontally),
            )
        }
    }
    Any ideas why this happens? Do I need a constraint mechanism or something for the FAB?
    m
    f
    t
    • 4
    • 7
  • m

    Mehdi Haghgoo

    09/02/2020, 2:12 PM
    Please correct me if I'm wrong. Jetpack Compose only allows certain modifiers on the children of a given built-in Composable (e.g. Column, Stack, etc.). It seems like every time I change the parent composable, some errors pop-up on the modifiers that are used on the current composable, requiring new imports. Why is that so?
    t
    n
    • 3
    • 3
  • t

    Timo Drick

    09/02/2020, 2:26 PM
    I am working on get flow working for endless scrolling (LazyColumnFor/LazyRowFor) lists. (Including error handling, retry and load on demand) Maybe someone can review the code to check if this is correct (For me it works fine 🙂 but maybe i missed something escepcially with the Channel stuff)
    • 1
    • 2
  • b

    bruno.aybar

    09/02/2020, 2:41 PM
    Hello. I've been seen weird issues when dealing with TextFields. Basically, the touch area for every component is incorrect after the soft keyboard has been opened. (attaching video on the thread). I can easily reproduce in these scenarios: • having a list of textfields, and select on one that has to be moved by to display the keyboard. Touch is now not working as expected • having a textfield aligned at bottom, open keyboard. For this case, I checked Jetchat app to see how that's handled, because I'm not seeing the issue there. However, I'm also seeing that there, ScrollState is used (I haven't check what that exactly does, but I guess it's handling scroll manually?) I wonder if that is a known issue, a bug, or an expected behavior in which scroll has to be handled manually?
    m
    a
    +2
    • 5
    • 18
  • l

    loloof64

    09/02/2020, 5:01 PM
    Hi everyone ! What is the simpliest way to make a Text composable expend to take the size of all of its parent, and not the size of its content ?
    z
    h
    • 3
    • 11
  • t

    tcracknell

    09/02/2020, 6:16 PM
    Hello! Today, we return to our regularly scheduled biweekly releases. The latest Jetpack Compose minor release, alpha02, has just dropped; you can get it now on Google’s Maven Repository. Release notes are available at https://developer.android.com/jetpack/androidx/versions/all-channel. Feedback is always welcome at https://issuetracker.google.com/issues/new?component=612128.
    🎉 43
    c
    • 2
    • 1
  • h

    Halil Ozercan

    09/02/2020, 8:13 PM
    In one of my composable components, I want to create a ViewModel and use it as the state source. However, once this composable is destroyed, viewModel should also get destroyed and next time the composable is rendered, a fresh new viewModel should be created. I achieved "creating a new viewModel" by introducing a remembered, random key as follows:
    // using itemId as key would still give me the same viewModel when this composable gets recreated
    val key = remember(itemId) { UUID.randomUUID().toString() }
    val commentsViewModel = viewModel<CommentsViewModel>(key = key)
    However, I cannot remove this particular viewModel from the store without removing other viewModels that were stored in the same place. How should I proceed with this? Is this an anti-pattern?
    i
    t
    s
    • 4
    • 14
Powered by Linen
Title
h

Halil Ozercan

09/02/2020, 8:13 PM
In one of my composable components, I want to create a ViewModel and use it as the state source. However, once this composable is destroyed, viewModel should also get destroyed and next time the composable is rendered, a fresh new viewModel should be created. I achieved "creating a new viewModel" by introducing a remembered, random key as follows:
// using itemId as key would still give me the same viewModel when this composable gets recreated
val key = remember(itemId) { UUID.randomUUID().toString() }
val commentsViewModel = viewModel<CommentsViewModel>(key = key)
However, I cannot remove this particular viewModel from the store without removing other viewModels that were stored in the same place. How should I proceed with this? Is this an anti-pattern?
i

Ian Lake

09/02/2020, 9:42 PM
This is a known issue. See the feature request https://issuetracker.google.com/issues/165642391
t

Timo Drick

09/02/2020, 10:50 PM
Maybe you mix something up here. But when you use remember {} also without any key the created value is lost when the composable is disposed. You can track the lifecycle of a composable with.
onActive { log("onActive") ; onDispose { log("dispose") } }
Also if you want to do some cleanup in your ViewModel class you can trigger it from onDispose
s

Sean McQuillan [G]

09/02/2020, 10:52 PM
Best advice – wait for the bug Ian linked to land. If you wanted to build something today, my recommendation would be to make an object that implements
CompositionLifecycleObserver
that's responsible for the cleanup code. https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/CompositionLifecycleObserver.kt;l=37?q=CompositionLifecycle
t

Timo Drick

09/02/2020, 10:52 PM
Maybe just create an instance of your ViewModel without using this special viewModel<...>() system
s

Sean McQuillan [G]

09/02/2020, 10:52 PM
Any object that implements that will call
onEnter
and
onLeave
when it's remembered (or forgotten) by composition
t

Timo Drick

09/02/2020, 10:54 PM
Maybe also viewModel is not what you want. Just use a normal class
i

Ian Lake

09/02/2020, 11:16 PM
You'd need to use
viewModel
if you want to have state that is retained over configuration changes (
remember
and the like do not do that)
t

Timo Drick

09/03/2020, 12:00 AM
You could just use
rememberSavedInstanceState
This will maybe later also keeps it state when you are using a navigation framework and the screen is still in backstack.
i

Ian Lake

09/03/2020, 12:39 AM
Both
viewModel
and
rememberSavedInstanceState
would work with the upcoming Navigation framework integration
👍 1
They aren't interchangable though - what you can save in saved instance state is much, much more restrictive than what you can save in a ViewModel
h

Halil Ozercan

09/03/2020, 6:39 AM
As this is just an experiment, it's best to wait for the fix to land
Thanks everyone 👍
View count: 3