July 2, 2023

Android - Jetpack Compose trial and error

After getting to a dead end with a Jetpack Compose tutorial, I decide to just try things. I set up two buttons. One will exit, the other will increment a count. This is not too hard. The next trick is to modify the text in one of the Text items to show the count.

Those pesky imports

I start using something new like Button or Spacer, and android studio shows it to me in red (to clue me in that it doesn't know what it is). Typically this means I need to add an import to the top of my file. How am I supposed to know what?

Type ALT-Enter and it will automatically insert something somehow that works.

Focus

I am used to "focus follows mouse" on my linux system. So I expect to put the mouse into the "window" in android studio that shows me MainActivity.kt and just start typing. For whatever reason, android studio always directs focus to the device manager and makes me crazy. An easy fix seems to be to detach the device manager by clicking on the little box thing at the upper right.

Modify text at run time

This involves weird rocket science. The second video (State and Jetpack compose) is a typical example of the rubbish you find, even on the Android developer site. It introduces a construct called "OutlinedTextField()", never really explains it, and when I try to use it, the compiler scolds me that it is an "experimental feature" and won't even compile my code. He says you will see this a million times if you look at JetPack Compose code!
var text by remember { mutableStateOf("") }
To use "by" with a var, you will need to introduce these imports by hand:
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue // only if using var
He says this is a known IDE bug.

He looks pretty good, and the above link is part 2 of a 7 part series on "Compose State" written in March of 2021.

In part 1, he gives this code as a quiz. I can add it to my current Compose experiment, and amazingly it works and I can play with it. Each time I click the button, the button grows, doubling in size (1-2-4-8-...).

@Composable fun Foo() {
  var text by remember { mutableStateOf("sam") }

  Button(onClick = { text = "$text\n$text" }) {
    Text(text)
  }
}
So we have a button that can change its own label, which is something.
Have any comments? Questions? Drop me a line!

Adventures in Computing / tom@mmto.org