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

    voben

    11/18/2021, 12:19 AM
    How do I constrain the center horizontal axis of this Textfield so it sits at the bottom of the grey image and moves with height of the image? Currently I have all the views in a Box and I’m adding padding for the TextField to align with the image. But if the image is shorter for example, I want the TextView to move up with it
    c
    t
    • 3
    • 6
  • c

    Colton Idle

    11/18/2021, 3:38 AM
    LazyRow has a contentPadding argument, but Row doesn't (even though you can make Row scrollable). Why is that? Or is there another way you're "supposed" to apply contentPadding in a Row?
    c
    a
    a
    • 4
    • 6
  • a

    Android75

    11/18/2021, 3:47 AM
    I 'm developing an app for smartphone and tablet. With xml was simple.. but with compose? I can put value or string into xml different folder and get if device is a smartphone or tablet. is there other method?
    c
    • 2
    • 4
  • e

    elye

    11/18/2021, 5:10 AM
    Hi, how can I effectively measure the complete Jetpack Compose rendering time? I use the function below, but it is not working, since the function call completed before the rendering of the UI is completed.
    @Composable
        override fun Content() {
            val elapsedTime= measureTimeMillis {
                MyDeepHierarchyJetpackComposeDrawing()
            }
            Log.d("Tracking", "Time used $elapsedTime")
        }
    Thanks!
    w
    r
    s
    • 4
    • 4
  • z

    Zoltan Demant

    11/18/2021, 9:13 AM
    If I render
    Screen
    and I can guarantee that its immutable, would it recompose fewer times/perform better if I wrapped it in a
    ScreenWrapper
    marked with
    @Immutable
    ? I cant mark the actual screen, but I can use a value/inline class for the wrapper.
    c
    z
    • 3
    • 4
  • a

    AmrJyniat

    11/18/2021, 11:25 AM
    How to use
    rememberSaveable
    with
    FocusRequester
    ? it gives me a crash.
    z
    • 2
    • 3
  • l

    loloof64

    11/18/2021, 12:24 PM
    Hi ! I'm using
    coroutineScope.launch {
    in order to start a coroutine in my code. But is there a variant of
    launch
    which runs the coroutine for a given amount of time, instead of infinitely ? Because otherwise, I'm afraid my code, which is a bit a kind of spaghetti as now, will be worse.
    c
    • 2
    • 2
  • m

    miqbaldc

    11/18/2021, 3:27 PM
    Anyone occurred the same issue/crash?
    Fatal Exception: java.lang.IllegalStateException: Compose assumes that all pointer ids in MotionEvents are first provided alongside ACTION_DOWN or ACTION_POINTER_DOWN.  This appears not to have been the case
    stacktrace.cpp
    g
    • 2
    • 4
  • v

    Vlad Gorbunov

    11/18/2021, 7:39 PM
    Hello, i didn’t manage to find answer myself and after googling a bit I decided to try it here Is there a way to support gboard image & video content insertion (gifs/stickers) in compose
    TextField
    ? For
    EditText
    i’ve used this..
    ViewCompat.setOnReceiveContentListener(chatInput.textInput, arrayOf("image/*", "video/*"))
    is there an option to not insert custom
    AndroidView
    ? 🤞
    s
    • 2
    • 3
  • j

    jeff

    11/18/2021, 9:07 PM
    I feel like this must be easy but I'm drawing a blank: I have a
    Column
    with 2 children. I want the second child's height to be exactly 100.dp, and the first child's height to take up the remainder. What's the easiest way to accomplish that? Putting
    Modifier.fillMaxHeight
    on the first child doesn't seem to cut it
    i
    • 2
    • 2
  • c

    Chris Fillmore

    11/18/2021, 10:29 PM
    I have a utility function which `remember`s a call to
    flowWithLifecycle
    , and I’m wondering if it’s wise (some code in thread)
    a
    l
    • 3
    • 14
  • b

    Bradleycorn

    11/19/2021, 1:42 AM
    I have a
    ClickableText
    (with an annotated string), and I only handle clicks on a certain portion of the string, like this:
    onClick = { pos ->
        if (pos in linkStart..linkEnd) {
            onLoginClicked()
        }
    }
    How can I test this? I need a way in the test to click on a certain position (string index) in the text.
    performClick()
    doesn’t take any parameters that I could use to click at a certain position. Using
    performTouchInput()
    let’s me move by a number of pixels, but I’m not sure how that helps since I need to click based on string position.
    b
    z
    • 3
    • 14
  • s

    Slackbot

    11/19/2021, 1:48 AM
    This message was deleted.
    r
    b
    • 3
    • 2
  • c

    Colton Idle

    11/19/2021, 5:46 AM
    For anyone that's savy with animation. A technique I've been using a lot is Crossfade{ } with a Button and when that button is making a network call, it crossfades into a CircularProgressBar. My "problem" is that I want the progressBar to be in the dead center of where the Button would have been. Leaving me to think... Crossfade is the wrong thing to use? Any other approaches you all would try? The only thing that comes to mind to me is to instead just create a composable where I change the alpha of the Button, and the progressBar so that the button is still measured, it's just not visible. Edit: Actually I looked at the code for Crossfade, and internally it seems to be changing alpha (which makes sense, I just didn't think about it before). If that's the case though... why do the contents inside shift around like the composable was removed from the tree entirely?
    a
    a
    • 3
    • 5
  • r

    rattleshirt

    11/19/2021, 8:18 AM
    What is the recommended way to avoid calling Android APIs from a
    @Preview
    ? For example
    rememberPermissionState
    has calls to
    Context
    or when remembering some specific Android API like MediaPlayer. Should those be provided through a
    CompositionLocalProvider
    at the root level or is there some other way to “fake” these?
    p
    • 2
    • 3
  • a

    Abhinav Sharma

    11/19/2021, 9:13 AM
    Hello, I am trying to write screenshot tests for
    HorizontalTrayUi()
    and
    TrayItemUi()
    Its easy to test
    TrayItemUi()
    in isolation by mocking
    TrayItemViewModel
    and its exposed state flows, but whats the recommended way to test
    HorizontalTrayUi()
    as it calls
    TrayItemUi()
    which then tries to create a viewModel using
    Hilt
    Here’s the structure
    @Composable
    fun HorizontalTrayUi(
    	trayModel: TrayModle,
    	viewModel: TrayViewModel = viewModel()
    ) {
    	Text(...) // title of the tray
    	LazyRow(..){
    		item -> {
    			TrayItemUi(item)
    		}
    	}
    }
    @Composable
    fun TrayItemUi(
    	item: TrayItemModel,
    	viewModel: TrayItemViewModel = viewModel()
    ) {
    	......
    }
    @Pedro Gomez
    p
    • 2
    • 3
  • t

    tylerwilson

    11/19/2021, 1:58 PM
    I am using DropdownMenu, with the offset param, to try to get it to show under where the press took place. But after get past a certain amount, it jumps all the way to the bottom of the view. Not sure why. Anybody have experience with this?
    a
    • 2
    • 1
  • d

    dimsuz

    11/19/2021, 3:01 PM
    I have a weird issue where
    Test
    composable in the snippet is not recomposed on state change, it's only called once. This seems to happen only if this Box is placed inside a
    sheetContent
    of
    BottomSheetScaffold
    :
    Box {
      var enable by remember { mutableStateOf(true) }
      println("enable out=$enable")
      Test(enable = enable)
      Button(onClick = { enable = !enable })
    }
    
    @Composable
    fun Test(enable: Boolean) {
      println("enable in=$enable")
      Text(text = enable.toString())
    }
    🤔 1
    a
    • 2
    • 7
  • j

    Jérémy CROS

    11/19/2021, 4:51 PM
    Hi guys 🙂 How would I disable accessibility on a
    Surface
    element? It’s an app for blind people and we have another mean of describing the content of the view with talkback Something like
    importantForAccessibility="noHideDescendants"
    a
    • 2
    • 1
  • b

    Bradleycorn

    11/19/2021, 7:40 PM
    Testing problem … please help, this has been driving me nuts! I have a simple `TextField`:
    TextField( value = myText,
        onValueChanged = { new -> myText = new },
        modifier = Modifier.testTag("MyInput"))
    And I’m trying to set some text in the text field in a test:
    composeTestRule.onNodeWithTag("MyInput").performTextInput("Test")
    My test fails, and I get the error:
    No input session started. Missing a focus?
    What am I doing wrong here? Doing some digging into the testing source and debugging the nodes, it looks like the
    TextField
    node doesn’t get focused for some reason. I tried adding a
    performClick()
    before setting the text, but that didn’t help either. The node still has
    focused =  false
    … What am I missing?
    l
    j
    c
    • 4
    • 7
  • a

    AmrJyniat

    11/20/2021, 6:53 AM
    How to make 
    ScaffoldState
     work with 
    CompositionLocalProvider
     to control the drawer open/close from anywhere in my fragment?
    b
    • 2
    • 4
  • a

    Adib Faramarzi

    11/20/2021, 10:35 AM
    Is there any APIs for being notified about an animation being finished in
    AnimatedVisibility
    ? (like
    onFinishedListener
    )
    m
    • 2
    • 3
  • m

    Mehdi Haghgoo

    11/20/2021, 8:47 PM
    Which artifact for livedata integration? androidx.compose.runtime:runtime-livedata or androidx.lifecycle:lifecycle-viewmodel-compose?
    i
    • 2
    • 3
  • u

    ursus

    11/20/2021, 9:25 PM
    Has someone integrated Dagger in such a way where dagger provides Screen composables? if so, how, ifi ts just
    () -> @Composable Unit
    lamdas? Qualifieres everywhere? Or maybe some typesafe object based Screen? is that a bad idea? (since it doesnt really compose if needed, same way fragments sort of did)
    b
    i
    • 3
    • 3
  • s

    skwalking

    11/21/2021, 7:05 AM
    @Composable
    fun GetContentExample() {
        val context = LocalContext.current
        var directoryUri by remember { mutableStateOf<Uri?>(null) }
        //val imageUri = mutableListOf<Uri?>()
        //val cR = context.contentResolver
    
        val launcher =
            rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri: Uri? ->
                directoryUri = uri
            }
        Column(modifier = Modifier.fillMaxSize()) {
    
            Button(onClick = { launcher.launch(directoryUri) }) {
                Text(text = "Load Image")
    
            }
    
            val documentFile = directoryUri?.let { DocumentFile.fromTreeUri(context, it) }
            val files = documentFile?.listFiles()
    
            val pathList = mutableListOf<DocumentFile>()
    
            files?.forEach { file ->
                if (file.type == "image/jpeg") {
                    pathList.add(file)
                }
            }
    
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(items = pathList) { path ->
                    Text(text = path.uri.toString())
                    Image(
                        painter = rememberImagePainter(path.uri),
                        contentDescription = "My Image"
                    )
                    Spacer(modifier = Modifier.height(20.dp))
                }
            }
        }
    }
    Help Text appearing but not the images. Here I'm first taking access to pictures folder then wanna show it on LazyColumn... It'll be good if you provide source I can read to know how to display, copy images from one folder to another 🙂
    :thread-please: 4
    c
    z
    • 3
    • 2
  • d

    dimsuz

    11/21/2021, 4:53 PM
    If I'd like to draw an inner (inset) shadow, what are my options? Not supported by the framework, but can I do it by hand maybe?
    c
    n
    • 3
    • 4
  • k

    K Merle

    11/22/2021, 6:01 AM
    I've added navigation animation to my project, and all my heavy computations that I could find are done on IO dispatcher, however, navigation animation still has little stutter during initial animation. Any tips on how to avoid this?
    z
    • 2
    • 1
  • n

    Napa Ram

    11/22/2021, 6:17 AM
    HI Team i am working on app which is only for tablet for all the resolution and i am facing issue to create UI as pixel perfect can anyone help me how i can create UI as pixel perfect in compose
    c
    c
    • 3
    • 4
  • z

    ziv kesten

    11/22/2021, 9:25 AM
    When setting ripple effect for a Row, i use rememberRipple but the ripple is not bounded to the rounded corners of the row. Is there anything off with the ripple implementation here?
    modifier = Modifier
        .padding(horizontal = 26.dp)
        .background(colorResource(R.color.lemonade_cloud), shape = RoundedCornerShape(7.dp))
        .fillMaxWidth()
        .wrapContentHeight()
        .clickable(onClick = {
            onLogoutClicked.invoke()
        }, indication = rememberRipple(bounded = true),
            interactionSource = remember { MutableInteractionSource() })
        .padding(vertical = 15.dp, horizontal = 20.dp),
    z
    • 2
    • 2
  • m

    Mehdi Haghgoo

    11/22/2021, 10:24 AM
    Does a ViewModel member have to be defined to be of a State<> type in order to invoke recomposion on change?
    n
    z
    c
    • 4
    • 16
Powered by Linen
Title
m

Mehdi Haghgoo

11/22/2021, 10:24 AM
Does a ViewModel member have to be defined to be of a State<> type in order to invoke recomposion on change?
n

nitrog42

11/22/2021, 10:35 AM
a state will trigger recomposition on change, but it doesn't have to be on the viewmodel part, ie collectAsState;observeAsState;produceState which will transform anything in a state that will trigger recomposition
➕ 1
your viewmodel member should be a flow or livedata or anything observable though, if it's just a var String for example, you should probably use a State (mutableStateOf) as you said, or it won't trigger any recomposition on the UI part
➕ 1
m

Mehdi Haghgoo

11/22/2021, 10:40 AM
I have a list stored in my ViewModel, it is LiveData<String>, and using observeAsState() does not give me the updated list in the Compose code.
n

nitrog42

11/22/2021, 10:44 AM
https://developer.android.com/jetpack/compose/state#use-other-types-of-state-in-jetpack-compose
Without the code it can be hard to understand what happens but if you use a MutableList it can cause this issue, even though with a LiveData I think it should work 🤔
m

Mehdi Haghgoo

11/22/2021, 10:50 AM
Hmm, I am seeing some red warnings in the doc 😄 Maybe that includes what I have done. Pasting the code in a bit.
class MainViewModel : ViewModel() {
    // TODO: Implement the ViewModel

    private val _currentMessage: MutableLiveData<String> = MutableLiveData("")
    private val _messages: MutableLiveData<MutableList<String>> = MutableLiveData()

    val messages: LiveData<MutableList<String>> = _messages

    val currentMessage: LiveData<String> = _currentMessage


    fun setCurrentMessage(message:String){
        _currentMessage.value = message
    }

    fun onAddMessage(message: String){
//        val temp = mutableListOf(message).apply{
//            _messages.value?.let { addAll(it) }
//        }
//        _messages.value = temp
        _messages.value?.add(message)
        Log.d("MainViewModel", "onAddMessage: New message added: $message. Total: ${_messages.value?.size}")
    }
}
Code that uses it:
Column{
    Log.d("MainFragment", "onCreateView: number of messages: ${messages?.size}")
    messages?.forEach { msg -> Text(msg, Modifier.padding(8.dp)) }
}
n

nitrog42

11/22/2021, 10:53 AM
I think your issue is _messages contains no value 🙂
private val _messages: MutableLiveData<MutableList<String>> = MutableLiveData()
-> _messages is empty, you need to either use MutableLiveData(mutableList()) or pass the list (as in your commented code)
but honnestly if you are doing a 100% compose new project, you should probably use
val message = mutableStateListOf()
➕ 3
m

Mehdi Haghgoo

11/22/2021, 11:08 AM
I assume _messages should be updated with ViewModel.onAddMessage(message).
👍 1
z

Zach Klippenstein (he/him) [MOD]

11/22/2021, 3:57 PM
A mutable list inside a state holder (a MutableState, StateFlow, LiveData, etc) is always a smell. Either use an immutable list or that mutableStateListOf. Assigning the same instance of a list to a state holder generally won't re-emit because the same list instance is always equal to itself.
➕ 1
c

Colton Idle

11/22/2021, 6:17 PM
A mutable list inside a state holder (a MutableState, StateFlow, LiveData, etc) is always a smell.
Makes sense.
Either use an immutable list
ok
or that mutableStateListOf
I would assume mutableStateListOf is the thing I should reach for first typically?
z

Zach Klippenstein (he/him) [MOD]

11/22/2021, 6:40 PM
I don’t think there's a single right answer. Depends on other things, there are trade-offs as with anything. Immutable data structures are often generally easier to reason about in async/concurrent environments.
👍 1
➕ 1
c

Colton Idle

11/22/2021, 6:50 PM
Yeah, typically I've always chosen immutable first... but compose has thrown me in a loop because of snapshot state that basically acts like it's mutable and it feels like its magic to not have to call .copy eveywhere lol
z

Zach Klippenstein (he/him) [MOD]

11/24/2021, 3:43 PM
Not sure if this will help but I wrote something about this yesterday: https://dev.to/zachklipp/two-mutables-dont-make-a-right-2kgp
➕ 2
View count: 1