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

    Kazemihabib1996

    04/30/2020, 12:35 PM
    Any chance we could use drawLayout with Dialogs in future? I'm trying to implement Overshoot animation with Dialogs
    Transition(
                definition = transDef,
                initState = AnimState.StartScale,
                toState = AnimState.EndScale
            ) { state ->
                Box(
                    modifier = Modifier.drawLayer(
                        scaleX = state[scale],
                        scaleY = state[scale]
                    )
                ) {
                    Dialog(onCloseRequest = onDismiss) {
                    ...
    This doesn't work and I hope this works in future 🙂 And using
    Dialog(onCloseRequest = onDismiss) {
                        Surface(
                            shape = MaterialTheme.shapes.medium, modifier = Modifier.drawLayer(
                                scaleX = state[scale],
                                scaleY = state[scale]
                            )
                        ) {
                        ...
    Just overshoots inside of the dialog not the dialog it self.
    m
    a
    • 3
    • 11
  • l

    len

    04/30/2020, 1:24 PM
    Is it possible (or planned) to draw a
    Text
    with outline? This was done with
    Paint.Style.STROKE
    , but there's no painter on
    Text
    parameters. I want to draw a text in white with a black border (like a shadow, but without blur)
    n
    l
    s
    • 4
    • 15
  • k

    Klaas Kabini

    04/30/2020, 6:24 PM
    Are coroutines supported in dev10 and does kapt play well with compose in this release?
    i
    • 2
    • 1
  • l

    Leland Richardson [G]

    04/30/2020, 6:41 PM
    yeah, i’d still like to do that. Right now there are still parts of the runtime APIs that would make this possible that are getting changed significantly, so i’d rather wait until those are closer to a “final” state
    🎉 6
    t
    • 2
    • 1
  • g

    Guy Bieber

    04/30/2020, 8:34 PM
    Is there an easy way to rotate an Image in compose?
    z
    • 2
    • 3
  • m

    manueldidonna

    04/30/2020, 9:43 PM
    Which is the best way to start an activity from a composable function and receives a result?
    a
    • 2
    • 5
  • s

    shikasd

    04/30/2020, 11:30 PM
    Are kotlin compiler sources of version 1.3.70 used for compose available anywhere? I am especially curious regarding solution for issues reported here.
    l
    • 2
    • 1
  • c

    codeslubber

    05/01/2020, 12:13 AM
    I am updating an android app I have had out there a long time. (Not using Compose in it yet, want to.. 🙂 ).. Question is, I am running this app on a Pixel4XL and it was originally written a while ago. I have a screen where you use a slider to set a target amount and it’s too small. Just read a bunch of stuff and it seems like I literally have to make a duplicate layout for higher density phones? I guess that’s what I have to do? my other question is how is Compose going to handle this? Thanks.
    l
    z
    r
    • 4
    • 19
  • f

    flosch

    05/01/2020, 8:53 AM
    Regarding testing with the `AndroidComposeTestRule`: What is the reason that I cannot declare
    <activity android:name="androidx.activity.ComponentActivity" />
    in the
    androidTest/AndroidManifest.xml
    but have to do it in
    main/AndroidManifest.xml
    ? 🤔
    l
    • 2
    • 5
  • m

    manueldidonna

    05/01/2020, 9:56 AM
    Do we need to avoid deep "view" hierarchy in compose as we usually do with the native android view system? https://developer.android.com/training/improving-layouts/optimizing-layout
    l
    z
    • 3
    • 3
  • s

    Sheroz Nazhmudinov

    05/01/2020, 12:14 PM
    Hey, i was trying out
    Transition
    in Compose, and had couple of questions. First is about
    transitionDefinition
    - i see that it’s an equivalent of value animator (correct me if i’m wrong). Is there a way to set the duration to it, and delay before the start? Second is about the
    Transition
    composable - is there a way to start the transition based on the user event (e.g., click)? Any hints/suggestions would be appreciated! 🙂
    z
    k
    • 3
    • 4
  • b

    Brian Norman

    05/01/2020, 3:43 PM
    Hey everyone, I'm new to Compose so pardon the potentially stupid question... I've got a Column of Composables that I'd like to filter based on a search bar, but I'm wondering how I can get the search bar's text lifted to its parent composable? I'm running into issues where if I pass a
    @Model
    object into the Search Bar composable from the parent then it'll get reset every time I type (I'm guessing this is because the parent re-renders causing the Search Bar re-renders)... If anyone's done this and could share how they've done it or point me in the right direction that would be super helpful! Thanks 🙂
    k
    • 2
    • 9
  • k

    kartoffelsup

    05/01/2020, 5:20 PM
    Hi, I just updated to dev10 and now I am getting the following during build:
    e: java.lang.AbstractMethodError: androidx.compose.plugins.kotlin.ComposeIrGenerationExtension.generate(Lorg/jetbrains/kotlin/ir/declarations/IrFile;Lorg/jetbrains/kotlin/backend/common/BackendContext;Lorg/jetbrains/kotlin/resolve/BindingContext;)V
    	at org.jetbrains.kotlin.backend.jvm.JvmBackendFacade.doGenerateFilesInternal$backend_jvm(JvmBackendFacade.kt:86)
    	at org.jetbrains.kotlin.backend.jvm.JvmBackendFacade.doGenerateFilesInternal$backend_jvm$default(JvmBackendFacade.kt:64)
    	at org.jetbrains.kotlin.backend.jvm.JvmBackendFacade.doGenerateFilesInternal$backend_jvm(JvmBackendFacade.kt:52)
    	at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.generateModule(JvmIrCodegenFactory.kt:36)
    	at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.doGenerateFiles(KotlinCodegenFacade.java:47)
    	at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:39)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:638)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:198)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:172)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:56)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:85)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:43)
    	at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:104)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:349)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:105)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:237)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:37)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:79)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:91)
    	at org.jetbrains.kotlin.daemon.CompileServiceImplBase.execIncrementalCompiler(CompileServiceImpl.kt:606)
    	at org.jetbrains.kotlin.daemon.CompileServiceImplBase.access$execIncrementalCompiler(CompileServiceImpl.kt:99)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1645)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
    	at sun.rmi.transport.Transport$1.run(Transport.java:200)
    	at sun.rmi.transport.Transport$1.run(Transport.java:197)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    	at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	at java.lang.Thread.run(Thread.java:748)
    anything I need to do to get dev10 working? Code is here: https://github.com/kartoffelsup/nuntius-app/commit/754e261591d180031b26cb4030ad27d59726151e - if I downgrade to dev09 it works fine again.
    l
    l
    • 3
    • 3
  • r

    Rooparsh

    05/02/2020, 2:04 PM
    Hi, just a newbie to Compose. Trying to show a list of data with bottom app bar. I have used scaffold as a parent with AdapterList as body content and bottomappbar. The problem is my AdapterList is being overlapped with bottomappbar and I can't seem to find any way around it. I am using dev09 . I know its childish mistake.
    k
    s
    l
    • 4
    • 23
  • s

    Sheroz Nazhmudinov

    05/02/2020, 2:12 PM
    Hey, how can I access displayMetrics in compose to get the screen density?
    m
    k
    • 3
    • 3
  • k

    karandeep singh

    05/02/2020, 7:20 PM
    An attempt to create a shimmer effect in compose. currently implemented using canvas and linear gradient. Would love to know if there could be a better/efficient way to do this.
    VID-20200503-WA0000.mp4
    👍 10
    z
    l
    +2
    • 5
    • 37
  • l

    Luca

    05/02/2020, 9:54 PM
    Has anyone been able to use compose with the kotlin-multiplatform plugin instead of the kotlin-android plugin? The composeOptions I set do not seem to be applying and I get a
    java.lang.NoSuchMethodError: No static method setContent$default
    runtime error. Is there another way to set kotlinCompilerVersion and kotlinCompilerExtensionVersion with the multiplatform plugin?
    j
    • 2
    • 1
  • l

    Lilly

    05/03/2020, 12:11 AM
    Is it possible to use camera features with compose. I'm thinking about SurfaceView...
    z
    • 2
    • 3
  • k

    karandeep singh

    05/03/2020, 7:26 PM
    @Composable
    fun SomeComposableFunction() {
        val t = animatedFloat(0f)
        Canvas(modifier = Modifier.fillMaxWidth()) {
    
            // this gives error during compile/build
            onActive {
    
            }
    
    
    
            //Can't do this as well
            val someValue = remember {
    
            }
    
    
    
        }
    }
    is this expected behaviour? we can't access Composables inside lambda's which are in turn inside some composable?
    a
    • 2
    • 4
  • a

    Ali Zargar Shabestari

    05/03/2020, 8:16 PM
    I'm getting:
    e: java.lang.IllegalStateException: Backend Internal error: Exception during code generation
    whenever I use view binding in a project with compose enabled. Is that a bug? I'm using
    dev10
    z
    b
    • 3
    • 3
  • k

    karandeep singh

    05/03/2020, 8:28 PM
    can @Compose annotated functions return values in newer apis now?
    t
    a
    v
    • 4
    • 13
  • b

    bohregard

    05/04/2020, 2:51 AM
    What's the reason this works:
    val context = ContextAmbient.current
    Card(modifier = Modifier.padding(8.dp) + Modifier.fillMaxWidth()) {
            Button(onClick = {
                Log.d(TAG, "Test")
                Toast.makeText(context, "Toast me bro", Toast.LENGTH_SHORT)
                    .show()
            }) {
                Text(text = "Test")
            }
        }
    }
    but this doesn't
    Card(modifier = Modifier.padding(8.dp) + Modifier.fillMaxWidth()) {
            Button(onClick = {
                Log.d(TAG, "Test")
                Toast.makeText(ContextAmbient.current, "Toast me bro", Toast.LENGTH_SHORT)
                    .show()
            }) {
                Text(text = "Test")
            }
        }
    }
    a
    • 2
    • 2
  • m

    manueldidonna

    05/04/2020, 2:08 PM
    I've made thit list with compose. Are these performances normal/expected? Gist: https://gist.github.com/manueldidonna/1eef3017a4ff4e42865641482ea78817
    🤔 2
    l
    r
    a
    • 4
    • 22
  • d

    dagomni

    05/04/2020, 4:28 PM
    I guess until you implement support for Kotlin 1.4 it won't work, but I have to ask Is there any way to make Compose work with 1.4? 😛 I get this error, related to IR
    java.lang.NoSuchMethodError: org.jetbrains.kotlin.ir.expressions.impl.IrBlockBodyImpl.<init>(IILkotlin/jvm/functions/Function1;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
    l
    s
    • 3
    • 6
  • g

    Gabriel Feo

    05/04/2020, 5:08 PM
    Will this actually compile with the import to the platform Activity extension, or is it a tooling error?
    l
    a
    • 3
    • 7
  • z

    Zach Klippenstein (he/him) [MOD]

    05/04/2020, 5:56 PM
    Question about
    AdapterList
    performance: with
    RecyclerView
    , when using
    DiffUtil
    to calculate list changes, it’s recommended to run the diff calculation on a background thread since it can be slow. This makes it tricky to use with declarative programming, because state updates to the list don’t synchronously get propagated down the tree (e.g.
    EditText
    in an item view causes a new list to be emitted with new text, but that text doesn’t get bound to the actual view until a few main loop iterations later, which causes state to get out of sync when typing fast). What implications does this have for
    AdapterList
    in Compose? Add/remove item animations can be done at the per-item level, which seems straightforward enough. But if the list is re-ordered, or items are inserted anywhere other than the end of the list, does
    AdapterList
    preserve composable state/groups by keying on the list items (i.e. using `key`/`Pivotal` machinery)? If it does, does it process those changes more efficiently than
    DiffUtil
    ? Does this question not even make sense in the Compose world?
    v
    l
    c
    • 4
    • 12
  • b

    bohregard

    05/05/2020, 3:44 AM
    Is there known issues with the preview in Dev10 in the latest canary android studio? I'm getting this error in every method that has a preview annotation:
    java.lang.NoClassDefFoundError: Could not initialize class kotlinx.coroutines.Dispatchers   at androidx.ui.core.WrappedComposition$setContent$1.invoke(Wrapper.kt:267)   at androidx.ui.core.WrappedComposition$setContent$1.invoke(Wrapper.kt:-1)   at androidx.compose.internal.RestartableFunction.invoke(RestartableFunction.kt:131)   at androidx.compose.internal.RestartableFunction.invoke(RestartableFunction.kt:-1)   at androidx.compose.ComposerKt.invokeComposable(Composer.kt:2106)   at androidx.compose.Recomposer.recompose$compose_runtime_release(Recomposer.kt:67)   at androidx.compose.CompositionImpl.setContent(Composition.kt:120)   at androidx.ui.core.WrappedComposition.setContent(Wrapper.kt:266)   at androidx.ui.core.WrappedComposition$setContent$2.invoke(Wrapper.kt:277)   at androidx.ui.core.WrappedComposition$setContent$2.invoke(Wrapper.kt:-1)   at androidx.ui.core.SavedStateDelegate.stopWaitingForStateRestoration(SavedStateDelegate.kt:84)   at androidx.ui.core.AndroidComposeView.onMeasure_Original(AndroidOwner.kt:455)   at androidx.ui.core.AndroidComposeView.onMeasure(AndroidOwner.kt:-1)   at android.view.View.measure_Original(View.java:24552)   at android.view.View_Delegate.measure(View_Delegate.java:80)   at android.view.View.measure(View.java:24516)   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)   at android.view.View.measure_Original(View.java:24552)   at android.view.View_Delegate.measure(View_Delegate.java:80)   at android.view.View.measure(View.java:24516)   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)   at android.view.View.measure_Original(View.java:24552)   at android.view.View_Delegate.measure(View_Delegate.java:80)   at android.view.View.measure(View.java:24516)   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:735)   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:481)   at android.view.View.measure_Original(View.java:24552)   at android.view.View_Delegate.measure(View_Delegate.java:80)   at android.view.View.measure(View.java:24516)   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)   at android.view.View.measure_Original(View.java:24552)   at android.view.View_Delegate.measure(View_Delegate.java:80)   at android.view.View.measure(View.java:24516) Copy stack to clipboard   Tip: Try to refresh the layout.
    i
    j
    • 3
    • 6
  • k

    Karthick

    05/05/2020, 5:50 AM
    why compose uses sp, dp, instead of raw number just like flutter...🤔
    b
    l
    +2
    • 5
    • 15
  • s

    Sam Woodall

    05/06/2020, 12:20 AM
    Hey, does anyone happen to know why onTap is called when I tap the red box here? but not the green box?
    setContent {
        Stack(Modifier.fillMaxSize()) {
            Box(backgroundColor = Color.Green, modifier = Modifier.tapGestureFilter(onTap = { ... }).preferredSize(200.dp).offset(200.dp, 200.dp))
            Box(backgroundColor = Color.Red, modifier = Modifier.preferredSize(100.dp))
        }
    }
    l
    • 2
    • 2
  • k

    Kazemihabib1996

    05/06/2020, 5:33 PM
    I'm trying the saveLayer and blendMode (I'm using this for the first time I've never used that before even in the previous android UIToolkit). So I followed this tutorial that's originally written for flutter https://stackoverflow.com/a/59650400/4146943 and I ended up with this code in jetpack compose
    @Composable
    fun testBlending2(modifier: Modifier = Modifier) {
    
        val paint = remember { Paint() }
    
    
        Canvas(modifier = modifier, onCanvas = {
            save()
            val rect = Rect(0f, 0f, 100f, 100f)
            drawRect(rect, paint.apply { color = Color.Red })
            saveLayer(Rect.fromLTWH(0f, 0f, size.width.value, size.height.value), paint.apply { BlendMode.multiply })
    
            drawRect(
                    rect.shift(Offset(20f, 20f)),
                    paint.apply { color = Color.Blue }
            )
            restore()
            restore()
        })
    }
    It's supposed to be but it just produces this image:

    https://i.stack.imgur.com/q3In0.png▾

    What am I doing wrong?
    👍 1
    r
    • 2
    • 27
Powered by Linen
Title
k

Kazemihabib1996

05/06/2020, 5:33 PM
I'm trying the saveLayer and blendMode (I'm using this for the first time I've never used that before even in the previous android UIToolkit). So I followed this tutorial that's originally written for flutter https://stackoverflow.com/a/59650400/4146943 and I ended up with this code in jetpack compose
@Composable
fun testBlending2(modifier: Modifier = Modifier) {

    val paint = remember { Paint() }


    Canvas(modifier = modifier, onCanvas = {
        save()
        val rect = Rect(0f, 0f, 100f, 100f)
        drawRect(rect, paint.apply { color = Color.Red })
        saveLayer(Rect.fromLTWH(0f, 0f, size.width.value, size.height.value), paint.apply { BlendMode.multiply })

        drawRect(
                rect.shift(Offset(20f, 20f)),
                paint.apply { color = Color.Blue }
        )
        restore()
        restore()
    })
}
It's supposed to be but it just produces this image:

https://i.stack.imgur.com/q3In0.png▾

What am I doing wrong?
👍 1
produced Image:
r

romainguy

05/06/2020, 5:39 PM
Note that you don’t need
saveLayer()
at all in this example
Anyway your problem is most likely that you should be writing:
paint.apply { blendMode = BlendMode.multiply }
You are not assigning the
BlendMode
to anything
k

Kazemihabib1996

05/06/2020, 5:43 PM
OOOPS, 😩 what a mistake 😞 how I didn't notice that Thank you
@romainguy I want to create a whole inside the below shape
@Composable
fun donat(modifier: Modifier = Modifier) {

    val icingPaint = remember {
        Paint().apply {
            asFrameworkPaint().pathEffect = ComposePathEffect(CornerPathEffect(40f), DiscretePathEffect(60f, 25f))
            color = Color(0xFF53250F)
        }
    }

    Canvas(modifier = modifier, onCanvas = {
        val center = Offset(size.minDimension.value / 2, size.minDimension.value / 2)
        val holePath = Path().apply {
            addOval(Rect.fromCircle(center, size.minDimension.value / 6))
        }

        val icing = Path().apply {
            addOval(Rect.fromCircle(center, size.minDimension.value / 2.5f))
            op(this, holePath, operation = PathOperation.difference).also {
                Log.d("OP RESULT", it.toString())
            }
        }


        drawPath(icing, icingPaint)
    })
}
but it doesn't work, but it works without
asFrameworkPaint().pathEffect = ComposePathEffect(CornerPathEffect(40f), DiscretePathEffect(60f, 25f))
without
asFrameworkPaint().pathEffect = ComposePathEffect(CornerPathEffect(40f), DiscretePathEffect(60f, 25f))
also I can create the whole with
nativeCanvas.clipPath(holePath.asAndroidPath(), Region.Op.DIFFERENCE)
with out removing that pathEffect.
r

romainguy

05/06/2020, 9:21 PM
It’s probably because your path effect is too wide and covering the hole
k

Kazemihabib1996

05/06/2020, 9:28 PM
I changed it to
asFrameworkPaint().pathEffect = DiscretePathEffect(1f, 1f)
but didn't help.
@romainguy Hi, again, sorry for asking a lot but I have another question about this stuff that's also been asked a lot with no answers in flutter github issues.(e.g https://github.com/flutter/flutter/issues/11002 ) You told that I don't need saveLayer at all in this example. can you please explain when we need to use saveLayer? I tried multiple situations and I got confused: 1)
drawRect(rect, paint.apply { color = Color.Red })

saveLayer(Rect.fromLTWH(0f, 0f, size.width.value, size.height.value), Paint().apply { blendMode = BlendMode.dstOut })

drawRect( rect.shift(Offset(20f, 20f)), paint.apply { color = Color.Blue } )

restore()
This example with `BlendMode.dstOut`not works correctly just the blue rectangle becomes black I don't understand why this happens. 2)
drawRect(rect, paint.apply { color = Color.Red })

drawRect( rect.shift(Offset(20f, 20f)), paint.apply {
          color = Color.Blue, blendMode = BlendMode.dstOut }
 )
This one is without saveLayer and just by applying the blendMode to the paint it works for
multiply
but doesn't work for
dstOut
and produced the same result like the previous one. 3) But if I call`saveLayer` with default blendMode of Paint, before both drawings in the above example it works I don't even need to
restore
it.
saveLayer(Rect.fromLTWH(0f, 0f, size.width.value, size.height.value), paint = Paint())
drawRect(rect, paint.apply { color = Color.Red })
drawRect(
                rect.shift(Offset(20f, 20f)),
                paint.apply {
                    color = Color.Blue
                    blendMode = BlendMode.dstOut
                }
        )
I don't understand it, why this happens? based on the docs
* Saves a copy of the current transform and clip on the save stack, and then
     * creates a new group which subsequent calls will become a part of. When the
     * save stack is later popped, the group will be flattened into a layer and
     * have the given `paint`'s [Paint.colorFilter] and [Paint.blendMode]
     * applied.
I think the
saveLayer
must be called between the first and second
drawRect
and then I should call the
restore
but here I should call it before both drawings and even I don't need to call
restore
.
r

romainguy

05/07/2020, 7:51 PM
Not sure why you keep mentioning Flutter 🙂
saveLayer
basically creates a temporary render target
think of it like a transparent bitmap
and some of the blending modes (like
DstOut
) may only provide the desired results you want when starting from a transparent content
The window of your app is opaque by default, so the alpha value is set to 1
The Android docs show what the different alpha compositing and blend modes do: https://developer.android.com/reference/android/graphics/PorterDuff.Mode
Anyway, so because multiply is not an alpha compositing mode, it works without saving a layer first
but
DstOut
does alpha composition, hence the
saveLayer
Note that
saveLayer
calls have a cost (memory and rendering performance) so use them sparingly (or at least watch performance)
Also, you don’t need the restore simply because Android does have its own restores to prevent mistakes from apps
But better to have a restore for every save
Oh and it wouldn’t make sense to call
saveLayer
for just one of the draw calls
k

Kazemihabib1996

05/07/2020, 8:03 PM
@romainguy Thank you for your nice explanation 👍 I got it finally. And about the flutter 😂 because in
BlendMode.kt
there are links to flutter docs and also the docs in that file is equal to to
<https://api.flutter.dev/flutter/dart-ui/BlendMode-class.html>
that was reason for using flutter docs and samples for learning this stuff 😁
r

romainguy

05/07/2020, 8:03 PM
Ah, that explains 🙂
😁 1
We should fix that :0
View count: 50