Skip to content

Instantly share code, notes, and snippets.

@realdadfish
Last active September 14, 2022 08:25
Show Gist options
  • Save realdadfish/508fbc9368722831faf8990236b6c06c to your computer and use it in GitHub Desktop.
Save realdadfish/508fbc9368722831faf8990236b6c06c to your computer and use it in GitHub Desktop.
Enable / disable buttons in list
...
<application>
<activity
android:name="androidx.activity.ComponentActivity"
android:exported="false"/>
</application>
...
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import kotlinx.coroutines.delay
@Composable
fun Parent() {
Column {
val enabled = remember { mutableStateOf(true) }
Child("First", enabled) { println("$it clicked") }
Child("Second", enabled) { println("$it clicked") }
Child("Third", enabled) { println("$it clicked") }
}
}
@Composable
fun Child(name: String, enabled: MutableState<Boolean>, action: (String) -> Unit) {
val clicked: MutableState<Boolean> = remember { mutableStateOf(false) }
val pendingLaunch: MutableState<Boolean> = remember { mutableStateOf(false) }
println("$name enabled: ${enabled.value}")
LaunchedEffect(key1 = clicked.value) {
if (clicked.value) {
println("$name: disabling global state")
enabled.value = false
delay(500)
pendingLaunch.value = true
}
}
LaunchedEffect(key1 = pendingLaunch.value) {
if(pendingLaunch.value) {
action(name)
println("$name: enabling global state")
enabled.value = true
clicked.value = false
pendingLaunch.value = false
}
}
Button(
enabled = enabled.value,
onClick = { clicked.value = true }) {
Text(text = name)
}
}
First enabled: true
Second enabled: true
Third enabled: true
Test: First clicked
Test: Second clicked
First enabled: true
First: disabling global state
First enabled: false
Second enabled: false
Third enabled: false
First clicked
First: enabling global state
First enabled: true
Second enabled: true
Third enabled: true
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class Test {
@get:Rule
val composeRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun test() {
with(composeRule) {
setContent { Parent() }
println("Test: First clicked")
onNodeWithText("First").performClick()
println("Test: Second clicked")
onNodeWithText("Second").performClick()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment