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

    Joost Klitsie

    08/12/2020, 10:00 AM
    Hello hello! I have some issue with text input and auto complete on an Android 6 device:
    OutlinedTextField(
                value = viewState.userName ?: "",
                onValueChange = viewModel::updateUserName,
                modifier = Modifier.fillMaxWidth(),
                label = { Text("User name") }
            )
    If I check the onValueChange callback, it is actually returning the wrong texts already (so I do not blame my own code behind it) It does look like it has to do with the autocomplete functionality on my other device with Android 8 it works fine
    z
    • 2
    • 3
  • f

    flosch

    08/12/2020, 10:07 AM
    Hey! assuming I have two (Outlined)TextFields, how can I switch focus from the first to the second after
    imeActionPerformed
    ?
    z
    • 2
    • 4
  • k

    KamilH

    08/12/2020, 2:04 PM
    What is the best place to browse Compose Samples? I can’t see them on cs.android.com In code I can see following path:
    androidx.compose.animation.samples.AnimateContent
    where can I find this sample?
    w
    • 2
    • 3
  • w

    William Barbosa

    08/12/2020, 2:15 PM
    Any tips on improving the performance of
    LazyColumnFor
    ? Even when the items are really flat the scrolling feels really jaggy. Is performance something that will be looked before the final release or am I holding it wrong?
    a
    t
    +4
    • 7
    • 11
  • c

    chris

    08/12/2020, 2:48 PM
    Tried to upgrade my project to dev-16 and I’m running into this error:
    e: java.lang.IllegalStateException: Symbol for public kotlin/Function3|null[0] is unbound
    Are there any known workarounds?
    s
    l
    • 3
    • 4
  • j

    jitinsharma

    08/12/2020, 3:16 PM
    I tried
    ViewGroup.setContent
    extension inside a
    BottomSheetDialog
    and it threw this exception
    java.lang.IllegalStateException: Composed into the View which doesn't propagate ViewTreeLifecycleOwner!
    Is this a known issue?
    i
    l
    v
    • 4
    • 9
  • k

    Klaas Kabini

    08/12/2020, 7:15 PM
    When is compose going to support this type of slider?
    j
    j
    +2
    • 5
    • 8
  • m

    manueldidonna

    08/12/2020, 7:38 PM
    Look behind the toolbar. The first visible item disappears as soon as it goes partially out of the screen
    20-08-12-03-11-33.mp4
    m
    • 2
    • 4
  • m

    Mehdi Haghgoo

    08/13/2020, 4:13 AM
    Hey! Is Container composable gone?
    z
    • 2
    • 1
  • m

    Mehdi Haghgoo

    08/13/2020, 4:14 AM
    Why are there so many Compose artifacts? It's a bit confusing. Is it not possible to put the whole Jetpack Compose library in one artifact?
    a
    g
    +3
    • 6
    • 8
  • a

    allan.conda

    08/13/2020, 8:17 AM
    About image loading:
    onCommit(url)
    part is causing infinite rendering loop. It’s weird because
    url
    doesn’t change.
    onCommit(1)
    or
    onCommit("a")
    works fine though. The weirdest thing is this is a reusable component, and it doesn’t occur on another screen. Any idea what’s wrong here?
    Untitled
    • 1
    • 3
  • b

    brandonmcansh

    08/13/2020, 1:03 PM
    Is a TextField not able to be used in a Dialog? Hitting this after adding characters
    ➕ 1
    d
    • 2
    • 1
  • b

    brandonmcansh

    08/13/2020, 1:34 PM
    is there a scheduled date for dev17? 😬
    k
    j
    • 3
    • 5
  • d

    Daniele B

    08/13/2020, 3:13 PM
    I set up my code like this, with a viewModel which is platform-independent:
    class MainActivity : AppCompatActivity() {
    
        val viewModel = MyViewModel()
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContent {
                MyTextComponent(viewModel.state)
            }
        }
    }
    
    @Composable
    @ExperimentalCoroutinesApi
    fun MyTextComponent(stateFlow: StateFlow<DataModel>) {
        val state by stateFlow.collectAsState()
        Text(text = state.mytext)
    }
    But on configuration changes (e.g. device rotation), the Activity gets destroyed, and so the viewModel. Is it better to tie the viewModel to the App class, or which other strategy do you suggest?
    h
    i
    +2
    • 5
    • 39
  • z

    Zach Klippenstein (he/him) [MOD]

    08/13/2020, 6:20 PM
    @Adam Powell I’m excited that
    onPreCommit
    and
    onCommit
    are being merged! They were pretty confusing.
    a
    a
    s
    • 4
    • 32
  • g

    Guy Bieber

    08/13/2020, 6:53 PM
    Is there a way to remove focus and the cursor from a textfield when the keyboard edit is done?
    @Composable
        override fun TextFieldWithHint(
            text: String,
            hint: @Composable() () -> Unit,
            onDone: (String) -> Unit,
            backgroundColor: Color,
            textColor : Color,
            fontSize: TextUnit,
            keyboardType: KeyboardType,
            visualTransformation: VisualTransformation,
            cursorColor : Color
        ) {
            val state = state { TextFieldValue(text) } //, textRange) }
            Surface(color = backgroundColor) { //}, border = Border(5.dp, Color.White)) {
                //Row {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    padding = 10.dp,
                    gravity = ContentGravity.CenterStart
                ) { //, padding = 15.dp) {
                    Stack(Modifier.weight(1f)) {
                        TextField(
                            //modifier = Modifier.fillMaxSize(),
                            value = state.value,
                            textStyle = TextStyle (
                                color = textColor,
                                fontSize = fontSize
                            ),
                            //textColor = textColor,
                            keyboardType = keyboardType,
                            imeAction = ImeAction.Done,
                            onValueChange = { state.value = it },
                            onImeActionPerformed = {
                                if (it == ImeAction.Done) {
                                    //todo remove hack when android fixes it
                                    //On older phones the shift key shows up as 00 in the string
                                    val char : Char = 0x00.toChar()
                                    var str = state.value.text.replace("${char}", "")
                                    onDone(str) //.text.substring(state.value.selection))
                                    hideKeyboard()
                                }
                            },
                            cursorColor = cursorColor,
                            visualTransformation = visualTransformation
                        )
                        if (state.value.text.isEmpty()) hint()
                    }
                }
            }
        }
    a
    • 2
    • 2
  • h

    Halil Ozercan

    08/13/2020, 8:27 PM
    I'm getting a compilation exception on my project.
    e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't transform method node:
    NewItem (Lkotlin/jvm/functions/Function1;Landroidx/compose/ui/Modifier;Landroidx/compose/runtime/Composer;III)V:
    It is hard for me to pinpoint exactly where it goes wrong because the stacktrace is rather large and there are no warnings on Android Studio. I'm sharing a gist which includes the whole stacktrace. https://gist.github.com/halilozercan/303908615b54f1bc29e6355515545018
    j
    z
    • 3
    • 7
  • p

    Patrick Yin

    08/13/2020, 9:20 PM
    For the Compose accessibility support, do we have a road map or a timeline in hand?
    a
    • 2
    • 9
  • u

    ursus

    08/14/2020, 8:39 PM
    Will compose attempt to handle navigation, backstack etc -- or will a "screen" framework be needed?
    v
    j
    +5
    • 8
    • 29
  • z

    Zach Klippenstein (he/him) [MOD]

    08/15/2020, 5:39 AM
    Thinking a bit about the implications of having a codebase that uses Compose with more than one type of
    Applier
    . Since composable functions carry no compile-time information about which “type of composition” they can be used in, it seems like it would be a real headache, in a large codebase, to try and keep functions for each different composition type separate. And the penalty for getting that wrong could only be, AFAIK, a runtime crash. It seems like it would be very useful for composable functions to effectively include the type of composition they can be used with in their actual type. This would both serve as documentation (“ah,
    foo()
    is a UI function, and
    bar()
    is a function for managing a 3D scene graph”), and for the compiler to actually do type checking. I’d be really curious to know what thoughts the Compose team has about this potential issue, and how to mitigate it.
    r
    l
    +4
    • 7
    • 17
  • g

    galex

    08/15/2020, 2:09 PM
    Hello, since I upgraded my project to
    0.1.0-dev16
    Android Studio can’t seem to generate any preview. Any idea? I’ve checked all versions everywhere, it seems OK. Here’s the error I see in the preview messages:
    java.lang.NoSuchMethodError: kotlin.jvm.internal.FunctionReferenceImpl.<init>(ILjava/lang/Object;Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;I)V
    	at androidx.compose.runtime.FrameManager$writeObserver$1.<init>(FrameManager.kt)
    	at androidx.compose.runtime.FrameManager.<clinit>(FrameManager.kt:176)
    	at androidx.compose.ui.platform.WrapperKt.setContent(Wrapper.kt:201)
    	at androidx.compose.ui.platform.WrapperKt.setContent$default(Wrapper.kt:196)
    	at androidx.ui.tooling.preview.ComposeViewAdapter.init$ui_tooling_release(ComposeViewAdapter.kt:283)
    	at androidx.ui.tooling.preview.ComposeViewAdapter.init(ComposeViewAdapter.kt:352)
    	at androidx.ui.tooling.preview.ComposeViewAdapter.<init>(ComposeViewAdapter.kt:138)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    	at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:399)
    	at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:189)
    	at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:147)
    	at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:303)
    	at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:417)
    	at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:428)
    	at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:332)
    	at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
    	at android.view.LayoutInflater.inflate(LayoutInflater.java:657)
    	at android.view.LayoutInflater.inflate(LayoutInflater.java:499)
    	at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:347)
    	at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:435)
    	at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:141)
    	at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:705)
    	at com.android.tools.idea.rendering.RenderTask.lambda$inflate$6(RenderTask.java:860)
    	at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$2.run(RenderExecutor.kt:170)
    	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)
    b
    m
    j
    • 4
    • 7
  • d

    dimsuz

    08/15/2020, 10:54 PM
    I noticed that inside
    ui-material
    library
    Typography
    is a data class which then gets used like this:
    internal val TypographyAmbient = staticAmbientOf { Typography() }
    I wonder why does it need to be explicitly constructed, why not have an
    object Typography
    and then
    staticAmbientOf { Typography }
    ? Asking because I'm making my own Typography object (non-material theme) and maybe I'll run into trouble with this.
    a
    • 2
    • 6
  • c

    carlos cdmp

    08/15/2020, 11:31 PM
    Is there any friendly way to create a custom view (or a viewholder for an item) with compose in a project using the old fashioned xml style?
    r
    • 2
    • 9
  • k

    Klaas Kabini

    08/16/2020, 6:18 AM
    @Adam Powell Which of the two is the recommended way of accessing ambients inside composable functions?
    1.
    val density = DensityAmbient.current
    //The code that uses density
    
    2.
    Providers(DensityAmbient provides density){
        // The code that use density
    }
    a
    • 2
    • 1
  • a

    andylamax

    08/16/2020, 6:52 AM
    Where can I read about ambients? I feel like I know so little about them
    a
    • 2
    • 4
  • d

    dimsuz

    08/16/2020, 12:33 PM
    Are there any recommendations on ways to extend the
    ColorPalette
    in
    ui-material
    ? For example my app draws a lot of diagrams and they all are styled in additional colors not covered by material spec, both dark/light variants. Currently one can't just add a color to a
    ColorPalette
    , and then there's an internal
    ObservableColorPalette
    trick which makes me think that dummily providing additional colors through an ambient might be a performance issue.
    a
    • 2
    • 2
  • z

    Zhelyazko Atanasov

    08/16/2020, 5:37 PM
    I just started reading and experimenting with Compose. So far it looks awesome - thanks to everyone involved in this enormous effort ❤️ As expected, I have a lot of questions 😄 After doing Android development for more than 10 years it's really hard to switch to Compose 😊 1. I've been reading the examples and quite often they use a Composable called
    Scaffold
    but reading the docs doesn't really explain what it is. Judging by the samples, it looks to be something like a
    CoordinatorLayout
    , am I right? 2. All the samples I've been reading use hardcoded values for dimensions (using the extension function
    Int.dp()
    ). Haven't read much about Theming yet, but is it possible to define something similar to custom attributes (
    attrs.xml
    ) or dimensions and reference those instead of the hardcoded values? Same for Strings - is there an alternative to
    strings.xml
    /
    plurals.xml
    3. Are there any more complex examples of a complete application? I'm about to read and play with Chris Banes' Tivi, as I'd like to see some samples on how to handle large app with many different screens, what are the best practices to integrate Composables with ViewModel... 4. And last one for the time being - so far I haven't seen/read anything about handling configuration changes (the most common one being screen rotation). In Activity's world we have
    onSaveInstanceState()
    - is there an alternative in Compose (other than ViewModel's SaveState)?
    a
    c
    • 3
    • 5
  • d

    dimsuz

    08/16/2020, 7:43 PM
    As a beginner I had a resource-loading related thought today. Many built-in composables accept either
    ImageAsset
    or
    VectorAsset
    (for example
    Icon
    ). And this is done using overloads. So if my composable has
    Icon
    as a child and I want to make the asset which I pass to it configurable, I have to introduce 2 overloads too. And this repeats up and up. The thought was: if
    ImageAsset
    and
    VectorAsset
    had some comon supertype this would be easier. For example some kind of
    sealed class Resource { class ImageAsset; class VectorAsset }
    . I suspect that current state of affairs had some reasoning behind it, does anyone know more?
    r
    a
    n
    • 4
    • 17
  • f

    Foso

    08/16/2020, 8:04 PM
    Is there a way to get a screenshot of a specific Composable as a Bitmap or any other file?
    m
    z
    +2
    • 5
    • 5
  • h

    Hanzhen

    08/16/2020, 10:11 PM
    Hi, is it possible to implement edge-to-edge by compose atm?
    r
    u
    +3
    • 6
    • 12
Powered by Linen
Title
h

Hanzhen

08/16/2020, 10:11 PM
Hi, is it possible to implement edge-to-edge by compose atm?
r

romainguy

08/16/2020, 10:13 PM
What's edge to edge?
u

ursus

08/16/2020, 11:05 PM
Drawing behind system bars
z

Zach Klippenstein (he/him) [MOD]

08/16/2020, 11:33 PM
Don't see why not. Composables are hosted in Android views, so anywhere a view can go, a composable can go.
👆 2
u

ursus

08/17/2020, 12:30 AM
he probably also means observing window insets to add padding bottom to recycling lists (with the clipPadding = false effect)
h

Hanzhen

08/17/2020, 7:06 AM
Exactly. How can I get Android view that hosts Composable?
t

Timo Drick

08/17/2020, 7:30 AM
I do it currently on my self but i think there will be also an easier Compose way soon.
private var insets by mutableStateOf(WindowInsetsCompat.Builder().build())

    private val systemWindowInsetListener = { view: View, insets: WindowInsetsCompat ->
        this.insets = insets
        insets
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ViewCompat.setOnApplyWindowInsetsListener(window.decorView.rootView, systemWindowInsetListener)
        setContent {
                AppThemeTransparent {
                    val insetPadding = with(DensityAmbient.current) {
                        val ltr = ConfigurationAmbient.current.localeLayoutDirection == LayoutDirection.Ltr
                        with(insets) {
                            InnerPadding(
                                    start = if (ltr) systemWindowInsetLeft.toDp() else systemWindowInsetRight.toDp(),
                                    top = systemWindowInsetTop.toDp(),
                                    end = if (ltr) systemWindowInsetRight.toDp() else systemWindowInsetLeft.toDp(),
                                    bottom = systemWindowInsetBottom.toDp()
                            )
                        }
                    }
👍 1
z

Zach Klippenstein (he/him) [MOD]

08/17/2020, 8:20 AM
ViewGroup.setContent
h

Hanzhen

08/17/2020, 11:12 AM
I created an ambient for it.
z

Zach Klippenstein (he/him) [MOD]

08/17/2020, 3:23 PM
Neat! There are a few issues with that code though: Don't do things like register listeners directly during composition. This function will set a new listener on every composition pass, which is unnecessary. It's can also be incorrect - it will set the listener even if the composition fails. It also leaks - this code doesn't remove the listener when the function is removed from the composition (parent stops calling it). To fix all of these, set the listener inside an
onActive
block, and use
onDisposed
to clean up. Also FYI you can share larger code snippets in slack, with syntax highlighting, by posting a Snippet.
👍 1
I also don't think you need to pass a View in, you can get the hosting view from
ViewAmbient
.
h

Hanzhen

08/17/2020, 7:05 PM
I can not get window inset with
onActive
, but I can by wrapping it in
remember
. Is it a bug? Also
ViewAmbient
can only be called inside Composable context.
c

cb

08/17/2020, 8:44 PM
Just going to leave this here: https://goo.gle/compose-insets. Still early days for it, but it should do everything you need
👍 4
View count: 3