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

    Chris Johnson

    09/07/2021, 11:18 PM
    Hello! I'm trying to implement a collapsing toolbar and I'm stuck on getting my toolbar content to scroll upwards (offscreen) along with my screen content. I've tried setting the offset of the container for the toolbar content to -(
    toolbarMaxHeight
    ) and then adding a spacer of height
    toolbarMaxHeight
    so it gives the content space to scroll upwards... but I'm ending up with a blank screen. Even though if I look in layout inspector it shows everything is where it's supposed to be. Is there a way to provide space to a composable so that it can be placed above the top of your screen and then allowed to scroll upwards? Code in comments
    • 1
    • 1
  • r

    rajesh

    09/08/2021, 12:23 AM
    How to trigger ViewModel function when user input changes on
    TextField
    ? I'm implementing search screen and need to make network call based on input value. I'm using paging for response data and collecting as
    LazyPagingItem
    c
    • 2
    • 1
  • s

    Sanendak

    09/08/2021, 3:37 AM
    What's the difference between this two approaches? And why first is preferable?
    @Composable
    fun TestScreen(viewModel: TestViewModel = hiltViewModel()) {
        //content
    }
    @Composable
    fun TestScreen() {
        val viewModel: TestViewModel = hiltViewModel()
        //content
    }
    l
    c
    • 3
    • 2
  • h

    Hatice Sarp

    09/08/2021, 6:21 AM
    Hello ! I have three underlying
    BasicInputText
    for change password. I use
    focusRequester
    to focus with BasicInputText. When I enter the screen, the last textfield is focused and the cursor is in that textfield. How can I change it to put it in the first textfield?
    z
    • 2
    • 6
  • t

    Tash

    09/08/2021, 6:45 AM
    Do inline/value classes need to be marked as
    @Immutable
    when they wrap primitives, or is that implied?
    z
    • 2
    • 2
  • r

    RE

    09/08/2021, 7:36 AM
    I saw compose added
    Modifier.blur()
    api, but it only can blur the content, is there any way to blur the background like this library? https://github.com/mmin18/RealtimeBlurView
    c
    • 2
    • 1
  • f

    fabiocollini

    09/08/2021, 8:29 AM
    hey all, I have a doubt about
    AndroidView
    . Using just views a
    FrameLayout
    above something else it doesn’t intercept any touches, instead using an
    AndroidView
    on top of a composable all the touches are intercepted
    🧵 1
    c
    a
    • 3
    • 8
  • a

    alorma

    09/08/2021, 11:13 AM
    Hello! Test problem here! test methods cannot be annotated wit
    @Composable
    but they need some composable code... code in 🧵
    a
    • 2
    • 6
  • p

    PHondogo

    09/08/2021, 12:00 PM
    When composable decompose and there was focused input with keyboard opened, then keyboard stayed opened. How to force close keyboard on such case?
    r
    • 2
    • 2
  • b

    bitkiller

    09/08/2021, 1:04 PM
    Column
      TextField
      DropdownMenu (height set)
    (X is 183 in my tests, haven't tested on other devices to see if that changes) If height <= X, ok, DropdownMenu shows up below the textfield. But if height >= X + 1, then it moves up covering the TextField.
    c
    • 2
    • 2
  • s

    Stefan Oltmann

    09/08/2021, 1:13 PM
    I use the "fill everything up" spacer a lot and want to define this for a util, but the "weight" method is not found. I guess because it depends on the scope. How must I modify this code so I can use
    FillSpacer()
    everywhere I would write the long form instead?
    @Composable
    fun FillSpacer() =
        Spacer(modifier = Modifier.weight(1.0f))
    ✅ 1
    f
    • 2
    • 2
  • e

    estevanfick

    09/08/2021, 2:30 PM
    I’m facing some issues trying to do this kind of flip animation. I’m using
    graphicsLayer
    to flip the card component and it’s working. But the problem is with the content, I dont know how to sync the both sides with the flip. Any tips?
    z
    c
    p
    • 4
    • 16
  • b

    Bradleycorn

    09/08/2021, 3:55 PM
    I have an app that uses a Material theme in light and dark variants … pretty standard stuff. The light theme uses a white surface color and a pretty dark (navy blue) primary color. So far so good… However, we have a few screens (formerly fragments) where the design calls for the color scheme to be inverted. That is, the dark (navy blue) color is used for the background (surface) and the content (text, textfields, etc) is white. I’m wondering what is the best way to deal with this? At first, I created a
    DarkSurface
    composable that wraps a surface and sets up some CompositionLocals to handle the color inversions. But the more I go down that path, the more cumbersome and wrong it seems. Now I’m wondering if I should create a new theme for these screens to use. Anyone else ran into something like this before and have any ideas on how to handle it?
    c
    n
    • 3
    • 4
  • c

    Colton Idle

    09/08/2021, 4:46 PM
    What's the quickest way to create a "theme overlay" in Compose? Like if I want my MaterialTheme, but I just want to swap color primary with Color.Red for example?
    j
    b
    • 3
    • 2
  • v

    Vinay Gaba

    09/08/2021, 5:25 PM
    Just added a section for long form content on JetpackCompose.app. Kicking things off with an article about "donut-hole" skipping in Compose. Give it a read here - https://jetpackcompose.app/articles/donut-hole-skipping-in-jetpack-compose
    👍🏻 1
    👍🏼 2
    👀 1
    👍🏾 1
    👍 11
    a
    • 2
    • 1
  • j

    Jan Skrasek

    09/08/2021, 5:33 PM
    What is an alternative for back handling in UI tests? Previously I used:
    Espresso.onView(ViewMatchers.isRoot()).perform(ViewActions.pressBack())
    With Compose I'm trying this:
    val keyEvent = NativeKeyEvent(NativeKeyEvent.ACTION_DOWN, NativeKeyEvent.KEYCODE_BACK)
    composeTestRule.onRoot().performKeyPress(KeyEvent(keyEvent))
    but getting:
    KeyEvent can't be processed because this key input node is not active.
    i
    • 2
    • 10
  • s

    Sergey Y.

    09/08/2021, 5:44 PM
    https://twitter.com/evowizz/status/1435309066826420224
    👀 8
    • 1
    • 1
  • m

    mattinger

    09/08/2021, 5:54 PM
    So i’m starting to play with BottomSheetModalLayout, the issue i’m having is that i’m in a Scaffold already, and using the NavController to control the content. If the content area has the BottomSheetModalLayout then it’s scrim doesn’t cover the TopAppBar of the main screen. If i move the BottomSheetModalLayout to be a parent of the Scaffold, i could presumably cover the TopAppBar with a scrim, but then i have to know at the top level what all my dialogs look like. I’m wondering what approach people are taking to solve this issue.
    • 1
    • 4
  • c

    CLOVIS

    09/08/2021, 7:43 PM
    Multiple Google engineers have emphasized that Compose (not UI) is designed to handle arbitrary mutable trees of data. I have a project (currently in the “research of feasibility” stage) that would require high-performance multi-threaded tree editions; is there someone knowledgeable to discuss this?
    k
    a
    • 3
    • 6
  • a

    Ahmed Sellami

    09/08/2021, 9:11 PM
    I am using this as a value for a path translation, and I don't know why it's not smooth and kinda late.
    val funnelTranslation by animateFloatAsState(
        targetValue = if (isDeleted.value)
            -radius * 3f - particleRadius
        else
            (offsetX.value - radius * 3f - particleRadius).coerceAtMost(0f)
    )
    isDeleted is a boolean state, and offsetX is an Animateable. Usage:
    Box {
        Canvas(
            Modifier.height(imageSizeDp)
        )
        {
            translate(funnelTranslation) {
                drawPath(
                    path = drawSideShape(radius = radius, particleRadius = particleRadius * 3 / 4f),
                    color = shoesArticle.color
                )
            }
        }
    }
    example.mp4
    a
    d
    • 3
    • 3
  • a

    adjpd

    09/08/2021, 10:42 PM
    Dialog
    and
    DropDownMenu
    unexpand and hide, respectively, when the user touches outside the composables. How can I implement this myself? I want to hide a composable if the user touches outside the composable.
    a
    • 2
    • 11
  • s

    Slackbot

    09/08/2021, 11:07 PM
    This message was deleted.
    a
    s
    a
    • 4
    • 4
  • b

    brabo-hi

    09/09/2021, 2:06 AM
    here is the error message i am getting : This version (1.0.2) of the Compose Compiler requires Kotlin version 1.5.21 but you appear to be using Kotlin version 1.5.30 which is not known to be compatible. Please fix your configuration (or
    suppressKotlinVersionCompatibilityCheck
    but don’t say I didn’t warn you!).
    ✅ 1
    a
    s
    • 3
    • 3
  • m

    Matej Drobnič

    09/09/2021, 6:16 AM
    Hello everybody. I have a more technical question regarding the layouting of compose. From documentation, compose has no double measuring. Instead, intrinsics are to be used. However, from what I see in the source code, by default, intrinsics just calls measure: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/MeasurePolicy.kt;l=138 What is the main difference then? Additionally, isn't that even worse than measuring? For example, if I want both max width and max height of some composable, before I do the final measure, I have to call both intrinsic methods, which will internally call measure twice, instead of just directly calling measure, which would give me both values in one call (but I'm not allowed to do that before final measure). Thanks.
    a
    • 2
    • 10
  • a

    allan.conda

    09/09/2021, 9:56 AM
    I want to encapsulate some composable code but I want to expose some of the internal state, but not all of it. Any idea how to tackle this on Compose? Or would I have to hoist the whole painter state in this example:
    fun DecoratedImage(
      data: Any?
    ) {
      val painter = rememberImagePainter(data) {
         crossfade(true)
         // lots of styling/customization
      }
      val state = (painter as? Success)?.state // I want to expose this state
      Image(painter)
    }
    a
    • 2
    • 2
  • m

    myanmarking

    09/09/2021, 11:15 AM
    whats the proper way to ‘store’ a computation by key?
    f
    • 2
    • 3
  • m

    myanmarking

    09/09/2021, 11:46 AM
    using accompanist coil library, when swapping an image url, the image disappears for a second, and then after the request completes it swaps the image. Is there any way to just swap the image when the loading is done ?
    a
    • 2
    • 2
  • m

    myanmarking

    09/09/2021, 12:20 PM
    Consider this trivial example. Are screen1 and screen2 equivalent, or is screen1 less efficient because it will recompose state2 when state1 changes?
    data class State(
    	val state1: State1,
    	val state2: State2
    )
    
    class ViewModel{
    	val state = flowOf<State?>(...)
    	.distinctUntilChanged()
    }
    
    fun screen1(){
    	Surface{
    		val viewState by viewModel.state.collectAsState(null)
    
    		composeFun1(viewState.state1)
    		composeFun2(viewState.state2)
    	}
    }
    
    fun screen2(){
    	Surface{
    		val viewState1 by viewModel.state.map{it.state1}.collectAsState(null)
    		val viewState2 by viewModel.state.map{it.state2}.collectAsState(null)
    
    		composeFun1(viewState1)
    		composeFun2(viewState2)
    	}
    }
    c
    a
    a
    • 4
    • 18
  • z

    Zoltan Demant

    09/09/2021, 12:24 PM
    Whats the recommended way to compute values in compose? If I have a
    Lazy<Foo>
    in my MainActivity that takes 1000 ms to resolve; how can I
    .get()
    it inside a
    @Composable
    function such that it happens in the background (e.g. with
    Dispatchers.Default
    )?
    t
    • 2
    • 7
  • a

    Anastasia Rozovskaya

    09/09/2021, 1:14 PM
    Hi! Is there a compose analog of
    animationDrawable
    or something which will enable me to have .png images replacing one another?
    d
    • 2
    • 12
Powered by Linen
Title
a

Anastasia Rozovskaya

09/09/2021, 1:14 PM
Hi! Is there a compose analog of
animationDrawable
or something which will enable me to have .png images replacing one another?
d

Doris Liu

09/09/2021, 6:45 PM
Recommend putting images in an
AnimatedContent
, where each image is associated with one state.
a

Anastasia Rozovskaya

09/10/2021, 9:00 AM
Could you, please, give an example? My final goal is to have a starting image transit to middle image and return to starting image - this behaviour is to be expected from one click on the first image.
d

Doris Liu

09/10/2021, 5:36 PM
So a click triggers an animation from image 1 -> 2 -> 1? It's doable. Can you give me a mock so I know my understanding is correct?
a

Anastasia Rozovskaya

09/11/2021, 1:50 PM
@Doris Liu Yes, that’s right. For now I can go from 1 to 2 like in a code below, but the intended behaviour is 1 -> 2 -> 1
var isClicked by remember { mutableStateOf(false) }
val imagePath: String =
    if (isClicked) pressedImagePath else defaultImagePath

AssetImage(
    path = imagePath,
    modifier = Modifier
        .size(68.dp)
        .clickable(enabled = !isDisabled) {
            isClicked = !isClicked
            onClick.invoke()
        })


// AssetImage is just a wrapper around CoilImage()
@Composable
fun AssetImage(
    path: String,
    modifier: Modifier,
    contentScale: ContentScale = ContentScale.Crop,
) {
    val context = LocalContext.current
    val imageLoader = buildImageLoader(context = context)
    CoilImage(
        imageModel = stringResource(id = R.string.assets_path) + path,
        imageLoader = imageLoader,
        modifier = modifier,
        contentScale = contentScale,
    )
}
I tried to use
LaunchedEffect()
but is seems useless for the case, and also
AnimatedContent
as you suggested, but didn’t get the result
I invented a thing with AnimatedContent. It works every odd click. The approach looks as worst practice example though)
d

Doris Liu

09/11/2021, 11:36 PM
I'd suggest something like:
var isClicked by remember { mutableStateOf(false) }
val transitionState = remember { MutableTransitionState(defaultImagePath) }
val transition = updateTranistion(transitionState)
transition.AnimatedContent(modifier = Modifier
        .clickable(enabled = !isDisabled) {
            isClicked = !isClicked
            transitionState.targetState = if (isClicked) pressedImagePath else defaultImagePath)
            onClick.invoke()
        }
) {
     AssetImage(Modifier.size(68.dp),path = it)
}
I suspect what you are trying to achieve is to change state when pressed, and again when released. If that's the case,
onClick
wouldn't give you enough info.
Consider the
detectTapGestures
API to get the accurate timing on pressed and released, like this: https://cs.android.com/androidx/platform/tools/dokka-devsite-plugin/+/master:testData/compose/samples/animation/samples/TransitionSamples.kt;l=64-72
a

Anastasia Rozovskaya

09/16/2021, 4:13 PM
Since the app was just a funny way of greeting colleagues on Programmer’s Day I had a deadline and decided to stop on the approach, which still worked half of the clicks, but that wasn’t too pronounced for users (nobody noticed, they were occupied by the game itself). Nevertheless, I hope to come across animations again and remember to solve this case.
Doris, thank you for your help and advices. I’ll post my half-solution here, may be the idea will be useful for somebody
var isClicked by remember { mutableStateOf(false) }

val imagePath: String =
    if (isClicked) pressedImagePath else defaultImagePath
val reversedImagePath: String =
    if (isClicked) defaultImagePath else pressedImagePath

val zIndex = if (isClicked) -1f else 1f

Box {
    AssetImage(
        path = imagePath,
        modifier = Modifier
            .size(68.dp)
            .zIndex(zIndex)
            .clip(RoundedCornerShape(50.dp))
            .clickable(enabled = !isDisabled) {
                isClicked = !isClicked
                onClick.invoke()
            }
    )

    AnimatedContent(targetState = reversedImagePath) { target ->
        AssetImage(path = target, modifier = Modifier
            .size(68.dp)
        )
    }
}
❤️ 1
View count: 1