Migrate activity project to use ktfmt
See go/why-ktfmt
BUG: 319663977
Change-Id: Ibd0f3679f736623c086f307be5c11b607e9d939b
diff --git a/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/ActivityComposeIssueRegistry.kt b/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/ActivityComposeIssueRegistry.kt
index 097257b..5eb0a32 100644
--- a/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/ActivityComposeIssueRegistry.kt
+++ b/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/ActivityComposeIssueRegistry.kt
@@ -22,20 +22,22 @@
import com.android.tools.lint.client.api.Vendor
import com.android.tools.lint.detector.api.CURRENT_API
-/**
- * [IssueRegistry] containing runtime specific lint issues.
- */
+/** [IssueRegistry] containing runtime specific lint issues. */
class ActivityComposeIssueRegistry : IssueRegistry() {
// Tests are run with this version. We ensure that with ApiLintVersionsTest
override val api = 14
override val minApi = CURRENT_API
- override val issues get() = listOf(
- ActivityResultLaunchDetector.LaunchDuringComposition,
- CollectProgressDetector.NoCollectCallFound
- )
- override val vendor = Vendor(
- vendorName = "Jetpack Activity Compose",
- identifier = "androidx.activity.compose",
- feedbackUrl = "https://issuetracker.google.com/issues/new?component=612128"
- )
+ override val issues
+ get() =
+ listOf(
+ ActivityResultLaunchDetector.LaunchDuringComposition,
+ CollectProgressDetector.NoCollectCallFound
+ )
+
+ override val vendor =
+ Vendor(
+ vendorName = "Jetpack Activity Compose",
+ identifier = "androidx.activity.compose",
+ feedbackUrl = "https://issuetracker.google.com/issues/new?component=612128"
+ )
}
diff --git a/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/ActivityResultLaunchDetector.kt b/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/ActivityResultLaunchDetector.kt
index 07c1e46..b9bd40fe 100644
--- a/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/ActivityResultLaunchDetector.kt
+++ b/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/ActivityResultLaunchDetector.kt
@@ -39,9 +39,7 @@
* composable function / lambda.
*/
class ActivityResultLaunchDetector : Detector(), SourceCodeScanner {
- override fun getApplicableMethodNames(): List<String> = listOf(
- Launch.shortName
- )
+ override fun getApplicableMethodNames(): List<String> = listOf(Launch.shortName)
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (!method.isInPackageName(PackageName)) return
@@ -57,19 +55,22 @@
}
companion object {
- val LaunchDuringComposition = Issue.create(
- "LaunchDuringComposition",
- "Calls to `launch` should happen inside of a SideEffect and not during composition",
- "Calling `launch` during composition is incorrect. Doing so will cause launch to be " +
- "called multiple times resulting in a RuntimeException. Instead, use `SideEffect`" +
- " and `launch` inside of the suspending block. The block will only run after a " +
- "successful composition.",
- Category.CORRECTNESS, 3, Severity.ERROR,
- Implementation(
- ActivityResultLaunchDetector::class.java,
- EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
+ val LaunchDuringComposition =
+ Issue.create(
+ "LaunchDuringComposition",
+ "Calls to `launch` should happen inside of a SideEffect and not during composition",
+ "Calling `launch` during composition is incorrect. Doing so will cause launch to be " +
+ "called multiple times resulting in a RuntimeException. Instead, use `SideEffect`" +
+ " and `launch` inside of the suspending block. The block will only run after a " +
+ "successful composition.",
+ Category.CORRECTNESS,
+ 3,
+ Severity.ERROR,
+ Implementation(
+ ActivityResultLaunchDetector::class.java,
+ EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
+ )
)
- )
}
}
diff --git a/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/BackHandlerOnBackPressedDetector.kt b/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/BackHandlerOnBackPressedDetector.kt
index 9822005..05c17bf 100644
--- a/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/BackHandlerOnBackPressedDetector.kt
+++ b/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/BackHandlerOnBackPressedDetector.kt
@@ -40,22 +40,19 @@
import org.jetbrains.uast.ULambdaExpression
class BackHandlerOnBackPressedDetector : Detector(), Detector.UastScanner, SourceCodeScanner {
- override fun getApplicableMethodNames(): List<String> = listOf(
- PredictiveBackHandler.shortName,
- BackHandler.shortName
- )
+ override fun getApplicableMethodNames(): List<String> =
+ listOf(PredictiveBackHandler.shortName, BackHandler.shortName)
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (method.isInPackageName(ComposePackageName)) {
// Find the back lambda
- val backLambda = computeKotlinArgumentMapping(node, method)
- .orEmpty()
- .filter { (_, parameter) ->
- parameter.name == OnBack
- }
- .keys
- .filterIsInstance<ULambdaExpression>()
- .firstOrNull() ?: return
+ val backLambda =
+ computeKotlinArgumentMapping(node, method)
+ .orEmpty()
+ .filter { (_, parameter) -> parameter.name == OnBack }
+ .keys
+ .filterIsInstance<ULambdaExpression>()
+ .firstOrNull() ?: return
// If the parameter is not referenced, immediately trigger the warning
val unreferencedParameter = backLambda.findUnreferencedParameters().firstOrNull()
@@ -65,12 +62,14 @@
val lambdaExpression = backLambda.sourcePsi as? KtLambdaExpression
// Find all of the reference inside of the lambda
val references =
- lambdaExpression?.functionLiteral
+ lambdaExpression
+ ?.functionLiteral
?.collectDescendantsOfType<KtSimpleNameExpression>()
// Check for references to OnBackPressed
- val matchingReferences = references?.filter {
- it.getReferencedName() == OnBackPressed.shortName
- }.orEmpty()
+ val matchingReferences =
+ references
+ ?.filter { it.getReferencedName() == OnBackPressed.shortName }
+ .orEmpty()
// If references call onBackPressed(), trigger the warning
if (matchingReferences.isNotEmpty()) {
matchingReferences.forEach { reference ->
@@ -88,23 +87,27 @@
}
companion object {
- val InvalidOnBackPressed = Issue.create(
- id = "OnBackPressedInsideOfBackHandler",
- briefDescription = "Do not call onBackPressed() within" +
- "BackHandler/PredictiveBackHandler",
- explanation = """You should not used OnBackPressedCallback for non-UI cases. If you
+ val InvalidOnBackPressed =
+ Issue.create(
+ id = "OnBackPressedInsideOfBackHandler",
+ briefDescription =
+ "Do not call onBackPressed() within" + "BackHandler/PredictiveBackHandler",
+ explanation =
+ """You should not used OnBackPressedCallback for non-UI cases. If you
|add a callback, you have to handle back completely in the callback.
""",
- category = Category.CORRECTNESS,
- severity = Severity.WARNING,
- implementation = Implementation(
- BackHandlerOnBackPressedDetector::class.java,
- EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
- )
- ).addMoreInfo(
- "https://developer.android.com/guide/navigation/custom-back/" +
- "predictive-back-gesture#ui-logic"
- )
+ category = Category.CORRECTNESS,
+ severity = Severity.WARNING,
+ implementation =
+ Implementation(
+ BackHandlerOnBackPressedDetector::class.java,
+ EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
+ )
+ )
+ .addMoreInfo(
+ "https://developer.android.com/guide/navigation/custom-back/" +
+ "predictive-back-gesture#ui-logic"
+ )
}
}
diff --git a/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/CollectProgressDetector.kt b/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/CollectProgressDetector.kt
index 8eaaea0..5d92c56 100644
--- a/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/CollectProgressDetector.kt
+++ b/activity/activity-compose-lint/src/main/java/androidx/activity/compose/lint/CollectProgressDetector.kt
@@ -40,28 +40,25 @@
import org.jetbrains.uast.ULambdaExpression
class CollectProgressDetector : Detector(), SourceCodeScanner {
- override fun getApplicableMethodNames(): List<String> = listOf(
- PredictiveBackHandler.shortName
- )
+ override fun getApplicableMethodNames(): List<String> = listOf(PredictiveBackHandler.shortName)
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (method.isInPackageName(PackageName)) {
// Find the back lambda
- val backLambda = computeKotlinArgumentMapping(node, method)
- .orEmpty()
- .filter { (_, parameter) ->
- parameter.name == "onBack"
- }
- .keys
- .filterIsInstance<ULambdaExpression>()
- .firstOrNull() ?: return
+ val backLambda =
+ computeKotlinArgumentMapping(node, method)
+ .orEmpty()
+ .filter { (_, parameter) -> parameter.name == "onBack" }
+ .keys
+ .filterIsInstance<ULambdaExpression>()
+ .firstOrNull() ?: return
// If the parameter is not referenced, immediately trigger the warning
val unreferencedParameter = backLambda.findUnreferencedParameters().firstOrNull()
if (unreferencedParameter != null) {
- val location = unreferencedParameter.parameter
- ?.let { context.getLocation(it) }
- ?: context.getLocation(backLambda)
+ val location =
+ unreferencedParameter.parameter?.let { context.getLocation(it) }
+ ?: context.getLocation(backLambda)
val name = unreferencedParameter.name
context.report(
NoCollectCallFound,
@@ -74,20 +71,24 @@
val lambdaExpression = backLambda.sourcePsi as? KtLambdaExpression
// Find all of the reference inside of the lambda
val references =
- lambdaExpression?.functionLiteral
+ lambdaExpression
+ ?.functionLiteral
?.collectDescendantsOfType<KtSimpleNameExpression>()
// Make sure one of the references calls collect
- val matchingReferences = references?.filter {
- it.getReferencedName() == Collect.shortName ||
- it.getReferencedName() == CollectIndexed.shortName ||
- it.getReferencedName() == CollectLatest.shortName
- }.orEmpty()
+ val matchingReferences =
+ references
+ ?.filter {
+ it.getReferencedName() == Collect.shortName ||
+ it.getReferencedName() == CollectIndexed.shortName ||
+ it.getReferencedName() == CollectLatest.shortName
+ }
+ .orEmpty()
// If no references call collect(), trigger the warning
if (matchingReferences.isEmpty()) {
val parameter = references?.firstOrNull()
- val location = parameter
- ?.let { context.getLocation(it) }
- ?: context.getLocation(backLambda)
+ val location =
+ parameter?.let { context.getLocation(it) }
+ ?: context.getLocation(backLambda)
val name = lambdaExpression?.name
context.report(
NoCollectCallFound,
@@ -101,19 +102,22 @@
}
companion object {
- val NoCollectCallFound = Issue.create(
- "NoCollectCallFound",
- "You must call collect on the given progress flow when using PredictiveBackHandler",
- "You must call collect on the progress in the onBack function. The collect call " +
- "is what properly splits the callback so it knows what to do when the back " +
- "gestures is started vs when it is completed. Failing to call collect will cause " +
- "all code in the block to run when the gesture is started.",
- Category.CORRECTNESS, 3, Severity.ERROR,
- Implementation(
- CollectProgressDetector::class.java,
- EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
+ val NoCollectCallFound =
+ Issue.create(
+ "NoCollectCallFound",
+ "You must call collect on the given progress flow when using PredictiveBackHandler",
+ "You must call collect on the progress in the onBack function. The collect call " +
+ "is what properly splits the callback so it knows what to do when the back " +
+ "gestures is started vs when it is completed. Failing to call collect will cause " +
+ "all code in the block to run when the gesture is started.",
+ Category.CORRECTNESS,
+ 3,
+ Severity.ERROR,
+ Implementation(
+ CollectProgressDetector::class.java,
+ EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
+ )
)
- )
}
}
diff --git a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/ActivityResultLaunchDetectorTest.kt b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/ActivityResultLaunchDetectorTest.kt
index df01c3d..2531f7b 100644
--- a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/ActivityResultLaunchDetectorTest.kt
+++ b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/ActivityResultLaunchDetectorTest.kt
@@ -31,32 +31,32 @@
/* ktlint-disable max-line-length */
@RunWith(JUnit4::class)
-/**
- * Test for [ActivityResultLaunchDetector].
- */
+/** Test for [ActivityResultLaunchDetector]. */
class ActivityResultLaunchDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = ActivityResultLaunchDetector()
override fun getIssues(): MutableList<Issue> =
mutableListOf(ActivityResultLaunchDetector.LaunchDuringComposition)
- private val MANAGED_ACTIVITY_RESULT_LAUNCHER = bytecodeStub(
- filename = "ActivityResultRegistry.kt",
- filepath = "androidx/activity/compose",
- checksum = 0xef067b97,
- source = """
+ private val MANAGED_ACTIVITY_RESULT_LAUNCHER =
+ bytecodeStub(
+ filename = "ActivityResultRegistry.kt",
+ filepath = "androidx/activity/compose",
+ checksum = 0xef067b97,
+ source =
+ """
package androidx.activity.compose
public class ManagedActivityResultLauncher<I> {
fun launch(input: I) { }
}
""",
- """
+ """
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJOBijgEuXiTs7P1UutSMwtyEkVYgtJLS7x
LlFi0GIAAJY6UNwvAAAA
""",
- """
+ """
androidx/activity/compose/ManagedActivityResultLauncher.class:
H4sIAAAAAAAA/51Ry24TMRQ9dpLJoy2ZtDSk5f2S0i6YNALxqiqVSohBKUhp
lU1WTmKlbhJPNfZE7S7fwh+wQmKBIpZ8FOJ6mg0tK7w499zjc+177V+/v/8A
@@ -71,13 +71,14 @@
yvAJH6XuG8gsWAaP03gPTygekKNCJ6x2kQmxFuJmiHVUieJWiBo2umAGm7jd
RcFgyeCOwV2DvMFySsoGK38AjaXx2SsDAAA=
"""
- )
+ )
@Test
fun errors() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -126,10 +127,10 @@
}
}
"""
- ),
- Stubs.Composable,
- MANAGED_ACTIVITY_RESULT_LAUNCHER
- )
+ ),
+ Stubs.Composable,
+ MANAGED_ACTIVITY_RESULT_LAUNCHER
+ )
.skipTestModes(TestMode.TYPE_ALIAS)
.run()
.expect(
@@ -162,9 +163,10 @@
@Test
fun noErrors() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -210,10 +212,10 @@
}
}
"""
- ),
- Stubs.Composable,
- MANAGED_ACTIVITY_RESULT_LAUNCHER
- )
+ ),
+ Stubs.Composable,
+ MANAGED_ACTIVITY_RESULT_LAUNCHER
+ )
.run()
.expectClean()
}
diff --git a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/ApiLintVersionsTest.kt b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/ApiLintVersionsTest.kt
index 952fc09..678b024 100644
--- a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/ApiLintVersionsTest.kt
+++ b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/ApiLintVersionsTest.kt
@@ -26,7 +26,6 @@
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
-
class ApiLintVersionsTest {
@Test
fun versionsCheck() {
diff --git a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/BackHandlerOnBackPressedDetectorTest.kt b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/BackHandlerOnBackPressedDetectorTest.kt
index d27ab06..d996b4a 100644
--- a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/BackHandlerOnBackPressedDetectorTest.kt
+++ b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/BackHandlerOnBackPressedDetectorTest.kt
@@ -33,9 +33,10 @@
@Test
fun expectPassOnBackPressed() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -50,18 +51,21 @@
dispatcher.onBackPressed()
}
"""
- ),
- Stubs.Composable,
- COMPONENT_ACTIVITY,
- ON_BACK_PRESSED_DISPATCHER,
- )
- .run().expectClean()
+ ),
+ Stubs.Composable,
+ COMPONENT_ACTIVITY,
+ ON_BACK_PRESSED_DISPATCHER,
+ )
+ .run()
+ .expectClean()
}
+
@Test
fun errors() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -88,13 +92,13 @@
}
}
"""
- ),
- Stubs.Composable,
- BACK_HANDLER,
- COMPONENT_ACTIVITY,
- ON_BACK_PRESSED_DISPATCHER,
- PREDICTIVE_BACK_HANDLER
- )
+ ),
+ Stubs.Composable,
+ BACK_HANDLER,
+ COMPONENT_ACTIVITY,
+ ON_BACK_PRESSED_DISPATCHER,
+ PREDICTIVE_BACK_HANDLER
+ )
.run()
.expect(
"""
diff --git a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/CollectProgressDetectorTest.kt b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/CollectProgressDetectorTest.kt
index e7e0f0f..d9771f2 100644
--- a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/CollectProgressDetectorTest.kt
+++ b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/CollectProgressDetectorTest.kt
@@ -33,9 +33,10 @@
@Test
fun errors() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -77,10 +78,10 @@
}
}
"""
- ),
- Stubs.Composable,
- PREDICTIVE_BACK_HANDLER
- )
+ ),
+ Stubs.Composable,
+ PREDICTIVE_BACK_HANDLER
+ )
.run()
.expect(
"""
@@ -112,9 +113,10 @@
@Test
fun errorWithNoCollect() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -127,10 +129,10 @@
}
}
"""
- ),
- Stubs.Composable,
- PREDICTIVE_BACK_HANDLER
- )
+ ),
+ Stubs.Composable,
+ PREDICTIVE_BACK_HANDLER
+ )
.run()
.expect(
"""
@@ -144,9 +146,10 @@
@Test
fun noErrors() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -202,19 +205,20 @@
}
}
"""
- ),
- Stubs.Composable,
- PREDICTIVE_BACK_HANDLER
- )
+ ),
+ Stubs.Composable,
+ PREDICTIVE_BACK_HANDLER
+ )
.run()
.expectClean()
}
@Test
fun noErrorsCollectIndexed() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -270,19 +274,20 @@
}
}
"""
- ),
- Stubs.Composable,
- PREDICTIVE_BACK_HANDLER
- )
+ ),
+ Stubs.Composable,
+ PREDICTIVE_BACK_HANDLER
+ )
.run()
.expectClean()
}
@Test
fun noErrorsCollectLatest() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.compose.runtime.Composable
@@ -338,10 +343,10 @@
}
}
"""
- ),
- Stubs.Composable,
- PREDICTIVE_BACK_HANDLER
- )
+ ),
+ Stubs.Composable,
+ PREDICTIVE_BACK_HANDLER
+ )
.run()
.expectClean()
}
diff --git a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/Stubs.kt b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/Stubs.kt
index b4a9de0..1b53c13 100644
--- a/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/Stubs.kt
+++ b/activity/activity-compose-lint/src/test/java/androidx/activity/compose/lint/Stubs.kt
@@ -19,10 +19,11 @@
import androidx.compose.lint.test.bytecodeStub
import com.android.tools.lint.checks.infrastructure.LintDetectorTest
-val BACK_HANDLER = bytecodeStub(
- filename = "BackHandler.kt",
- filepath = "androidx/activity/compose",
- checksum = 0x40a94587,
+val BACK_HANDLER =
+ bytecodeStub(
+ filename = "BackHandler.kt",
+ filepath = "androidx/activity/compose",
+ checksum = 0x40a94587,
"""
package androidx.activity.compose
@@ -33,13 +34,13 @@
enabled: Boolean = true,
onBack: () -> Unit) { }
""",
- """
+ """
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJWKM3AZcQlmZiXUpSfmVKhl5hcklmWWVKp
l5yfW5BfnCrE65SYnO0BlM9JLfIuEWILSS0u8S7hEuXiBqrQS61IzC3ISYUJ
KzFoMQAA3mTzZGMAAAA=
""",
- """
+ """
androidx/activity/compose/BackHandlerKt.class:
H4sIAAAAAAAA/4VSXU8TQRQ9s/1eoJQiCgURBQRE2YImPFRNlITQWNBY5QGe
ptuhTrudJbvTBl8Mf8Of4RvxwfDsjzLe2bZY4YEmnft17r3n3r2///z8BeAF
@@ -57,26 +58,27 @@
KqxfYLrX8hm9MbB01DuLWNQlSRXTJC1sRKDHcEi+onJmhMIxYmXMljFHL+6X
MY8HZSzg4TFYiEdYPEYyRCLEUoh89Nohlv8C003RZnYEAAA=
"""
-)
+ )
-val COMPONENT_ACTIVITY = bytecodeStub(
- "ComponentActivity.kt",
- "androidx/activity",
- 0xd291c9ac,
- """
+val COMPONENT_ACTIVITY =
+ bytecodeStub(
+ "ComponentActivity.kt",
+ "androidx/activity",
+ 0xd291c9ac,
+ """
package androidx.activity
class ComponentActivity {
fun onBackPressed() { }
}
""",
- """
+ """
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJWKM3AZcQlmZiXUpSfmVKhl5hcklmWWVKp
l5yfW5BfnCrE65SYnO0BlM9JLfIuEWILSS0u8S7hEuXiBqrQS61IzC3ISYUJ
KzFoMQAA3mTzZGMAAAA=
""",
- """
+ """
androidx/activity/ComponentActivity.class:
H4sIAAAAAAAA/41RTW8TMRB9481uyralm7ZAWuCEkGgrsWnFCVClthJSqrQg
QLnk5Oxa4Cax0dqJ2lt+C/+AExIHFHHsj0KMQ4QQXGrJb+a98fPH+Prnt+8A
@@ -89,26 +91,27 @@
kRZGgftzvIcHHJ+zHv5ttYeojdttrDEiC9BoYx0bPZDDJu70EDukDncdEodl
Tn4B9lImlUcCAAA=
"""
-)
+ )
-val ON_BACK_PRESSED_DISPATCHER = bytecodeStub(
- "OnBackPressedDispatcher.kt",
- "androidx/activity",
- 0x38be529,
- """
+val ON_BACK_PRESSED_DISPATCHER =
+ bytecodeStub(
+ "OnBackPressedDispatcher.kt",
+ "androidx/activity",
+ 0x38be529,
+ """
package androidx.activity
class OnBackPressedDispatcher {
fun onBackPressed() { }
}
""",
- """
+ """
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJWKM3AZcQlmZiXUpSfmVKhl5hcklmWWVKp
l5yfW5BfnCrE65SYnO0BlM9JLfIuEWILSS0u8S7hEuXiBqrQS61IzC3ISYUJ
KzFoMQAA3mTzZGMAAAA=
""",
- """
+ """
androidx/activity/OnBackPressedDispatcher.class:
H4sIAAAAAAAA/41R0UobQRQ9dza7savWjbY1xva9VnCj+GSLoC2FSFqLLXnJ
02R3qGOSWdmZBH3Lt/QP+lTogwQf+1Gld6KICEIH5tx7zp2zM/fun7+/rwDs
@@ -121,12 +124,13 @@
I90aBdZnuIqXHPdY9/9wsYughactLDEi8VBrYRkrXZDFMzzvIrSILV5YRBbz
nPwDYUKQQFkCAAA=
"""
-)
+ )
-val PREDICTIVE_BACK_HANDLER = LintDetectorTest.bytecode(
- "libs/predictivebackhandler.jar",
- LintDetectorTest.kotlin(
- """
+val PREDICTIVE_BACK_HANDLER =
+ LintDetectorTest.bytecode(
+ "libs/predictivebackhandler.jar",
+ LintDetectorTest.kotlin(
+ """
package androidx.activity.compose
import androidx.compose.runtime.Composable
@@ -136,14 +140,15 @@
enabled: Boolean = true,
onBack: (progress: String) -> Unit) { }
"""
- ).indented(),
- 0x7806fd68,
- """
+ )
+ .indented(),
+ 0x7806fd68,
+ """
META-INF/main.kotlin_module:
H4sIAAAAAAAA/2NgYGBmYGBgBGJWKM3ApcwlmZiXUpSfmVKhl5hcklmWWVKp
l5yfW5BfnCrEFpJaXOJdwiXKxQ0U0kutSMwtyIELKzFoMQAAfOuo51QAAAA=
""",
- """
+ """
androidx/activity/compose/TestKt.class:
H4sIAAAAAAAA/4VTW08TQRT+ZnvblltZRaFcFEEtImxBDQ81JkpCbKyVCPIg
8WHYDnXodpbsTht9MfwNX/0HvhEfDPHRH2U8s20BwYQmPZc535zznXNmf//5
@@ -163,4 +168,4 @@
vgEtYJV0hdKZFgq7SFQwWcEUSUxXMINbFdzG7C5YhDuY20UuQirCfAQnluTe
jY17Ee5HKP4FMROs2egEAAA=
"""
-)
+ )
diff --git a/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/BackHandlerSample.kt b/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/BackHandlerSample.kt
index debfb8a..87eeee4 100644
--- a/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/BackHandlerSample.kt
+++ b/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/BackHandlerSample.kt
@@ -34,10 +34,7 @@
fun BackHandler() {
var text by remember { mutableStateOf("") }
- TextField(
- value = text,
- onValueChange = { text = it }
- )
+ TextField(value = text, onValueChange = { text = it })
BackHandler(text.isNotEmpty()) {
// handle back event
@@ -49,17 +46,12 @@
fun PredictiveBack(callback: SampleCallbackHelper) {
var text by remember { mutableStateOf("") }
- TextField(
- value = text,
- onValueChange = { text = it }
- )
+ TextField(value = text, onValueChange = { text = it })
PredictiveBackHandler(text.isNotEmpty()) { progress: Flow<BackEventCompat> ->
callback.preparePop()
try {
- progress.collect { backEvent ->
- callback.updateProgress(backEvent.progress)
- }
+ progress.collect { backEvent -> callback.updateProgress(backEvent.progress) }
callback.popBackStack()
} catch (e: CancellationException) {
callback.cancelPop()
diff --git a/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/RememberLauncherForActivityResult.kt b/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/RememberLauncherForActivityResult.kt
index 75480ad..c9b22f4 100644
--- a/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/RememberLauncherForActivityResult.kt
+++ b/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/RememberLauncherForActivityResult.kt
@@ -35,13 +35,12 @@
@Composable
fun RememberLauncherForActivityResult() {
val result = remember { mutableStateOf<Bitmap?>(null) }
- val launcher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicturePreview()) {
- result.value = it
- }
+ val launcher =
+ rememberLauncherForActivityResult(ActivityResultContracts.TakePicturePreview()) {
+ result.value = it
+ }
- Button(onClick = { launcher.launch() }) {
- Text(text = "Take a picture")
- }
+ Button(onClick = { launcher.launch() }) { Text(text = "Take a picture") }
result.value?.let { image ->
Image(image.asImageBitmap(), null, modifier = Modifier.fillMaxWidth())
diff --git a/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/ReportLoadedSamples.kt b/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/ReportLoadedSamples.kt
index 8a4a86b..2ce77a1 100644
--- a/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/ReportLoadedSamples.kt
+++ b/activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/ReportLoadedSamples.kt
@@ -47,9 +47,7 @@
@Composable
fun ReportDrawnAfterSample() {
val lazyListState = remember { LazyListState() }
- ReportDrawnAfter {
- lazyListState.animateScrollToItem(10)
- }
+ ReportDrawnAfter { lazyListState.animateScrollToItem(10) }
}
@Sampled
diff --git a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/ActivityResultRegistryTest.kt b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/ActivityResultRegistryTest.kt
index b0b3fb0..45199b4 100644
--- a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/ActivityResultRegistryTest.kt
+++ b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/ActivityResultRegistryTest.kt
@@ -55,40 +55,38 @@
@MediumTest
@RunWith(AndroidJUnit4::class)
class ActivityResultRegistryTest {
- @get:Rule
- val composeTestRule = createComposeRule()
+ @get:Rule val composeTestRule = createComposeRule()
var launchCount = 0
- val registryOwner = object : ActivityResultRegistryOwner {
- override val activityResultRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- launchCount++
- }
+ val registryOwner =
+ object : ActivityResultRegistryOwner {
+ override val activityResultRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ launchCount++
+ }
+ }
}
- }
@Test
fun testLaunch() {
var launcher: ActivityResultLauncher<Intent>? by mutableStateOf(null)
composeTestRule.setContent {
- CompositionLocalProvider(
- LocalActivityResultRegistryOwner provides registryOwner
- ) {
- launcher = rememberLauncherForActivityResult(
- ActivityResultContracts.StartActivityForResult()
- ) {}
+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides registryOwner) {
+ launcher =
+ rememberLauncherForActivityResult(
+ ActivityResultContracts.StartActivityForResult()
+ ) {}
}
}
composeTestRule.runOnIdle {
launcher?.launch(Intent()) ?: fail("launcher was not composed")
- assertWithMessage("the registry was not invoked")
- .that(launchCount)
- .isEqualTo(1)
+ assertWithMessage("the registry was not invoked").that(launchCount).isEqualTo(1)
}
}
@@ -96,12 +94,11 @@
fun testGetContract() {
var launcher: ActivityResultLauncher<Intent>? by mutableStateOf(null)
composeTestRule.setContent {
- CompositionLocalProvider(
- LocalActivityResultRegistryOwner provides registryOwner
- ) {
- launcher = rememberLauncherForActivityResult(
- ActivityResultContracts.StartActivityForResult()
- ) {}
+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides registryOwner) {
+ launcher =
+ rememberLauncherForActivityResult(
+ ActivityResultContracts.StartActivityForResult()
+ ) {}
}
}
composeTestRule.runOnIdle {
@@ -115,12 +112,11 @@
fun testUnregister() {
var launcher: ManagedActivityResultLauncher<Intent, ActivityResult>? by mutableStateOf(null)
composeTestRule.setContent {
- CompositionLocalProvider(
- LocalActivityResultRegistryOwner provides registryOwner
- ) {
- launcher = rememberLauncherForActivityResult(
- ActivityResultContracts.StartActivityForResult()
- ) {}
+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides registryOwner) {
+ launcher =
+ rememberLauncherForActivityResult(
+ ActivityResultContracts.StartActivityForResult()
+ ) {}
}
}
composeTestRule.runOnIdle {
@@ -128,9 +124,11 @@
@Suppress("DEPRECATION") // the unregister method is deprecated
launcher?.unregister()
} catch (e: UnsupportedOperationException) {
- assertThat(e).hasMessageThat().contains(
- "Registration is automatically handled by rememberLauncherForActivityResult"
- )
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "Registration is automatically handled by rememberLauncherForActivityResult"
+ )
}
}
}
@@ -146,12 +144,11 @@
activityScenario.onActivity { activity ->
(activity as ComponentActivity).setContent {
- CompositionLocalProvider(
- LocalActivityResultRegistryOwner provides registryOwner
- ) {
- launcher = rememberLauncherForActivityResult(
- ActivityResultContracts.StartActivityForResult()
- ) {}
+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides registryOwner) {
+ launcher =
+ rememberLauncherForActivityResult(
+ ActivityResultContracts.StartActivityForResult()
+ ) {}
}
}
}
@@ -161,38 +158,37 @@
activityScenario.recreate()
- val restoredOwner = object : ActivityResultRegistryOwner {
- override val activityResultRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- launchCount++
- }
+ val restoredOwner =
+ object : ActivityResultRegistryOwner {
+ override val activityResultRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ launchCount++
+ }
+ }
}
- }
restoredOwner.activityResultRegistry.onRestoreInstanceState(savedState)
activityScenario.onActivity { activity ->
(activity as ComponentActivity).setContent {
- CompositionLocalProvider(
- LocalActivityResultRegistryOwner provides restoredOwner
- ) {
- launcher = rememberLauncherForActivityResult(
- ActivityResultContracts.StartActivityForResult()
- ) {}
+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides restoredOwner) {
+ launcher =
+ rememberLauncherForActivityResult(
+ ActivityResultContracts.StartActivityForResult()
+ ) {}
}
}
}
composeTestRule.runOnIdle {
launcher?.launch(Intent()) ?: fail("launcher was not composed")
- assertWithMessage("the registry was not invoked")
- .that(launchCount)
- .isEqualTo(1)
+ assertWithMessage("the registry was not invoked").that(launchCount).isEqualTo(1)
}
}
@@ -200,33 +196,34 @@
fun testRecomposeBeforeLaunch() {
var counter = 0
var code = 0
- val registry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- code = requestCode
+ val registry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ code = requestCode
+ }
}
- }
- val owner = object : ActivityResultRegistryOwner {
- override val activityResultRegistry = registry
- }
+ val owner =
+ object : ActivityResultRegistryOwner {
+ override val activityResultRegistry = registry
+ }
var recompose by mutableStateOf(false)
val launchChannel = Channel<Boolean>()
val launchFlow = launchChannel.receiveAsFlow()
composeTestRule.setContent {
- CompositionLocalProvider(
- LocalActivityResultRegistryOwner provides owner
- ) {
+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides owner) {
@Suppress("ControlFlowWithEmptyBody") // triggering recompose
if (recompose) {}
- val launcher = rememberLauncherForActivityResult(
- ActivityResultContracts.StartActivityForResult()
- ) {
- counter++
- }
+ val launcher =
+ rememberLauncherForActivityResult(
+ ActivityResultContracts.StartActivityForResult()
+ ) {
+ counter++
+ }
LaunchedEffect(Unit) {
launchFlow.collect { shouldLaunch ->
if (shouldLaunch) {
@@ -238,9 +235,7 @@
}
recompose = true
- composeTestRule.runOnIdle {
- assertThat(counter).isEqualTo(0)
- }
+ composeTestRule.runOnIdle { assertThat(counter).isEqualTo(0) }
launchChannel.trySend(true)
composeTestRule.runOnIdle {
registry.dispatchResult(code, RESULT_OK, Intent())
@@ -252,32 +247,33 @@
fun testRecomposeAfterLaunch() {
var counter = 0
var code = 0
- val registry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- code = requestCode
- launchCount++
+ val registry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ code = requestCode
+ launchCount++
+ }
}
- }
- val owner = object : ActivityResultRegistryOwner {
- override val activityResultRegistry = registry
- }
+ val owner =
+ object : ActivityResultRegistryOwner {
+ override val activityResultRegistry = registry
+ }
composeTestRule.setContent {
var recompose by remember { mutableStateOf(false) }
- CompositionLocalProvider(
- LocalActivityResultRegistryOwner provides owner
- ) {
+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides owner) {
@Suppress("ControlFlowWithEmptyBody") // triggering recompose
- if (recompose) { }
- val launcher = rememberLauncherForActivityResult(
- ActivityResultContracts.StartActivityForResult()
- ) {
- counter++
- }
+ if (recompose) {}
+ val launcher =
+ rememberLauncherForActivityResult(
+ ActivityResultContracts.StartActivityForResult()
+ ) {
+ counter++
+ }
Button(
onClick = {
launcher.launch(Intent())
@@ -300,31 +296,29 @@
fun testLaunchWithSameContract() {
var counter = 0
var code = 0
- val registry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- code = requestCode
- launchCount++
+ val registry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ code = requestCode
+ launchCount++
+ }
}
- }
- val owner = object : ActivityResultRegistryOwner {
- override val activityResultRegistry = registry
- }
+ val owner =
+ object : ActivityResultRegistryOwner {
+ override val activityResultRegistry = registry
+ }
val contract = ActivityResultContracts.StartActivityForResult()
composeTestRule.setContent {
var recompose by remember { mutableStateOf(false) }
- CompositionLocalProvider(
- LocalActivityResultRegistryOwner provides owner
- ) {
+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides owner) {
@Suppress("ControlFlowWithEmptyBody") // triggering recompose
- if (recompose) { }
- val launcher = rememberLauncherForActivityResult(contract) {
- counter++
- }
+ if (recompose) {}
+ val launcher = rememberLauncherForActivityResult(contract) { counter++ }
Button(
onClick = {
launcher.launch(Intent())
diff --git a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/BackHandlerTest.kt b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/BackHandlerTest.kt
index 1d6776c..a751992 100644
--- a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/BackHandlerTest.kt
+++ b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/BackHandlerTest.kt
@@ -41,8 +41,7 @@
@LargeTest
@RunWith(AndroidJUnit4::class)
class BackHandlerTest {
- @get:Rule
- val composeTestRule = createComposeRule()
+ @get:Rule val composeTestRule = createComposeRule()
@Test
fun testBackHandler() {
@@ -51,15 +50,11 @@
composeTestRule.setContent {
BackHandler { backCounter++ }
val dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
- Button(onClick = { dispatcher.onBackPressed() }) {
- Text(text = "Press Back")
- }
+ Button(onClick = { dispatcher.onBackPressed() }) { Text(text = "Press Back") }
}
composeTestRule.onNodeWithText("Press Back").performClick()
- composeTestRule.runOnIdle {
- assertThat(backCounter).isEqualTo(1)
- }
+ composeTestRule.runOnIdle { assertThat(backCounter).isEqualTo(1) }
}
@Test
@@ -84,8 +79,8 @@
}
/**
- * Test that [BackHandler] updates the dispatcher callback successfully when the
- * `onBack` function parameter changes
+ * Test that [BackHandler] updates the dispatcher callback successfully when the `onBack`
+ * function parameter changes
*/
@Test
fun testBackHandlerOnBackChanged() {
@@ -94,18 +89,12 @@
composeTestRule.setContent {
BackHandler(onBack = handler)
val dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
- Button(onClick = { dispatcher.onBackPressed() }) {
- Text(text = "Press Back")
- }
+ Button(onClick = { dispatcher.onBackPressed() }) { Text(text = "Press Back") }
}
composeTestRule.onNodeWithText("Press Back").performClick()
- composeTestRule.runOnIdle {
- handler = { results += "changed" }
- }
+ composeTestRule.runOnIdle { handler = { results += "changed" } }
composeTestRule.onNodeWithText("Press Back").performClick()
- composeTestRule.runOnIdle {
- assertThat(results).isEqualTo(listOf("initial", "changed"))
- }
+ composeTestRule.runOnIdle { assertThat(results).isEqualTo(listOf("initial", "changed")) }
}
/**
@@ -122,25 +111,21 @@
val dispatcherOwner =
object : OnBackPressedDispatcherOwner, LifecycleOwner by lifecycleOwner {
override val onBackPressedDispatcher = dispatcher
- }
- dispatcher.addCallback(lifecycleOwner) { }
+ }
+ dispatcher.addCallback(lifecycleOwner) {}
CompositionLocalProvider(
LocalOnBackPressedDispatcherOwner provides dispatcherOwner,
LocalLifecycleOwner provides lifecycleOwner
) {
BackHandler { interceptedBack = true }
}
- Button(onClick = { dispatcher.onBackPressed() }) {
- Text(text = "Press Back")
- }
+ Button(onClick = { dispatcher.onBackPressed() }) { Text(text = "Press Back") }
}
lifecycleOwner.currentState = Lifecycle.State.CREATED
lifecycleOwner.currentState = Lifecycle.State.RESUMED
composeTestRule.onNodeWithText("Press Back").performClick()
- composeTestRule.runOnIdle {
- assertThat(interceptedBack).isEqualTo(true)
- }
+ composeTestRule.runOnIdle { assertThat(interceptedBack).isEqualTo(true) }
}
}
diff --git a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/BackPressedDispatcherOwnerTest.kt b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/BackPressedDispatcherOwnerTest.kt
index 458eafa..84085c4 100644
--- a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/BackPressedDispatcherOwnerTest.kt
+++ b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/BackPressedDispatcherOwnerTest.kt
@@ -37,19 +37,14 @@
@LargeTest
@RunWith(AndroidJUnit4::class)
class BackPressedDispatcherOwnerTest {
- @get:Rule
- val composeTestRule = createComposeRule()
+ @get:Rule val composeTestRule = createComposeRule()
@Test
fun testGetBackPressedDispatcher() {
lateinit var dispatcherOwner: OnBackPressedDispatcherOwner
- composeTestRule.setContent {
- dispatcherOwner = LocalOnBackPressedDispatcherOwner.current!!
- }
+ composeTestRule.setContent { dispatcherOwner = LocalOnBackPressedDispatcherOwner.current!! }
- assertWithMessage("There should be a dispatcherOwner set")
- .that(dispatcherOwner)
- .isNotNull()
+ assertWithMessage("There should be a dispatcherOwner set").that(dispatcherOwner).isNotNull()
}
@Test
@@ -79,14 +74,10 @@
composeTestRule.setContent {
BackHandler { backCounter++ }
val dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
- Button(onClick = { dispatcher.onBackPressed() }) {
- Text(text = "Press Back")
- }
+ Button(onClick = { dispatcher.onBackPressed() }) { Text(text = "Press Back") }
}
composeTestRule.onNodeWithText("Press Back").performClick()
- composeTestRule.runOnIdle {
- assertThat(backCounter).isEqualTo(1)
- }
+ composeTestRule.runOnIdle { assertThat(backCounter).isEqualTo(1) }
}
}
diff --git a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/PredictiveBackHandlerTest.kt b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/PredictiveBackHandlerTest.kt
index e7bf0f8..8cc48ff 100644
--- a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/PredictiveBackHandlerTest.kt
+++ b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/PredictiveBackHandlerTest.kt
@@ -51,8 +51,7 @@
@LargeTest
@RunWith(AndroidJUnit4::class)
class PredictiveBackHandlerTestApi {
- @get:Rule
- val rule = createComposeRule()
+ @get:Rule val rule = createComposeRule()
private fun OnBackPressedDispatcher.startGestureBack() =
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
@@ -77,15 +76,11 @@
progress.collect()
}
val dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
- Button(onClick = { dispatcher.startGestureBack() }) {
- Text(text = "backPress")
- }
+ Button(onClick = { dispatcher.startGestureBack() }) { Text(text = "backPress") }
}
rule.onNodeWithText("backPress").performClick()
- rule.runOnIdle {
- assertThat(onStart).isTrue()
- }
+ rule.runOnIdle { assertThat(onStart).isTrue() }
}
@Test
@@ -99,17 +94,13 @@
counter++
}
dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
- Button(onClick = { dispatcher.startGestureBack() }) {
- Text(text = "backPress")
- }
+ Button(onClick = { dispatcher.startGestureBack() }) { Text(text = "backPress") }
}
rule.onNodeWithText("backPress").performClick()
dispatcher.api34Complete()
- rule.runOnIdle {
- assertThat(counter).isEqualTo(1)
- }
+ rule.runOnIdle { assertThat(counter).isEqualTo(1) }
}
@Test
@@ -133,9 +124,7 @@
dispatcher.startGestureBack()
dispatcher.api34Complete()
- rule.runOnIdle {
- assertThat(result).isEqualTo(listOf("onBack"))
- }
+ rule.runOnIdle { assertThat(result).isEqualTo(listOf("onBack")) }
enabled = false
rule.runOnIdle {
@@ -174,12 +163,8 @@
dispatcher.startGestureBack()
dispatcher.api34Complete()
- rule.waitUntil(1000) {
- result.size >= 3
- }
- rule.runOnIdle {
- assertThat(result).isEqualTo(listOf("start", "async", "complete"))
- }
+ rule.waitUntil(1000) { result.size >= 3 }
+ rule.runOnIdle { assertThat(result).isEqualTo(listOf("start", "async", "complete")) }
}
@Test
@@ -206,9 +191,7 @@
rule.waitUntil { asyncStarted }
dispatcher.startGestureBack()
dispatcher.api34Complete()
- rule.waitUntil(1000) {
- result.size >= 3
- }
+ rule.waitUntil(1000) { result.size >= 3 }
rule.runOnIdle {
// only second async work should complete
@@ -236,9 +219,7 @@
}
rule.onNodeWithText("backPress").performClick()
- rule.runOnIdle {
- assertThat(result).isEqualTo(listOf("child"))
- }
+ rule.runOnIdle { assertThat(result).isEqualTo(listOf("child")) }
}
@Test
@@ -261,9 +242,7 @@
}
rule.onNodeWithText("backPress").performClick()
- rule.runOnIdle {
- assertThat(result).isEqualTo(listOf("parent"))
- }
+ rule.runOnIdle { assertThat(result).isEqualTo(listOf("parent")) }
}
@Test
@@ -280,15 +259,11 @@
progress.collect()
}
val dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
- Button(onClick = { dispatcher.startGestureBack() }) {
- Text(text = "backPress")
- }
+ Button(onClick = { dispatcher.startGestureBack() }) { Text(text = "backPress") }
}
rule.onNodeWithText("backPress").performClick()
- rule.runOnIdle {
- assertThat(result).isEqualTo(listOf("second"))
- }
+ rule.runOnIdle { assertThat(result).isEqualTo(listOf("second")) }
}
@Test
@@ -311,37 +286,32 @@
}
rule.onNodeWithText("backPress").performClick()
- rule.runOnIdle {
- assertThat(result).isEqualTo(listOf("first"))
- }
+ rule.runOnIdle { assertThat(result).isEqualTo(listOf("first")) }
}
@Test
fun testBackHandlerOnBackChanged() {
val results = mutableListOf<String>()
- var handler by mutableStateOf<suspend (Flow<BackEventCompat>) -> Unit>(
- { progress ->
+ var handler by
+ mutableStateOf<suspend (Flow<BackEventCompat>) -> Unit>({ progress ->
results += "first"
progress.collect()
- }
- )
+ })
rule.setContent {
PredictiveBackHandler(onBack = handler)
val dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
- Button(onClick = { dispatcher.startGestureBack() }) {
- Text(text = "backPress")
+ Button(onClick = { dispatcher.startGestureBack() }) { Text(text = "backPress") }
+ }
+ rule.onNodeWithText("backPress").performClick()
+ rule.runOnIdle {
+ handler = { progress ->
+ results += "second"
+ progress.collect()
}
}
rule.onNodeWithText("backPress").performClick()
- rule.runOnIdle { handler = { progress ->
- results += "second"
- progress.collect()
- } }
- rule.onNodeWithText("backPress").performClick()
- rule.runOnIdle {
- assertThat(results).isEqualTo(listOf("first", "second"))
- }
+ rule.runOnIdle { assertThat(results).isEqualTo(listOf("first", "second")) }
}
@Test
@@ -354,7 +324,7 @@
object : OnBackPressedDispatcherOwner, LifecycleOwner by lifecycleOwner {
override val onBackPressedDispatcher = dispatcher
}
- dispatcher.addCallback(lifecycleOwner) { }
+ dispatcher.addCallback(lifecycleOwner) {}
CompositionLocalProvider(
LocalOnBackPressedDispatcherOwner provides dispatcherOwner,
LocalLifecycleOwner provides lifecycleOwner
@@ -364,18 +334,14 @@
progress.collect()
}
}
- Button(onClick = { dispatcher.startGestureBack() }) {
- Text(text = "backPressed")
- }
+ Button(onClick = { dispatcher.startGestureBack() }) { Text(text = "backPressed") }
}
lifecycleOwner.currentState = Lifecycle.State.CREATED
lifecycleOwner.currentState = Lifecycle.State.RESUMED
rule.onNodeWithText("backPressed").performClick()
- rule.runOnIdle {
- assertThat(interceptedBack).isEqualTo(true)
- }
+ rule.runOnIdle { assertThat(interceptedBack).isEqualTo(true) }
}
}
@@ -383,8 +349,7 @@
@RunWith(AndroidJUnit4::class)
@RequiresApi(34)
class PredictiveBackHandlerTestApi34 {
- @get:Rule
- val rule = createComposeRule()
+ @get:Rule val rule = createComposeRule()
@Test
fun testHandleOnProgress() {
@@ -392,9 +357,7 @@
var counter = 0
lateinit var dispatcher: OnBackPressedDispatcher
rule.setContent {
- PredictiveBackHandler { progress ->
- progress.collect { result += counter++ }
- }
+ PredictiveBackHandler { progress -> progress.collect { result += counter++ } }
dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
}
@@ -452,9 +415,7 @@
dispatcher.dispatchOnBackProgressed(fakeBackEventCompat())
dispatcher.dispatchOnBackCancelled()
- rule.runOnIdle {
- assertThat(result).isEqualTo(listOf("start", "progress"))
- }
+ rule.runOnIdle { assertThat(result).isEqualTo(listOf("start", "progress")) }
}
@Test
@@ -488,9 +449,7 @@
dispatcher.dispatchOnBackProgressed(fakeBackEventCompat())
dispatcher.dispatchOnBackProgressed(fakeBackEventCompat())
dispatcher.onBackPressed()
- rule.runOnIdle {
- assertThat(result).isEqualTo(listOf("progress", "progress", "complete"))
- }
+ rule.runOnIdle { assertThat(result).isEqualTo(listOf("progress", "progress", "complete")) }
}
@Test
@@ -525,14 +484,11 @@
}
}
-class TestOnBackPressedDispatcherOwner(
- override val lifecycle: Lifecycle
-) : OnBackPressedDispatcherOwner {
+class TestOnBackPressedDispatcherOwner(override val lifecycle: Lifecycle) :
+ OnBackPressedDispatcherOwner {
var fallbackCount = 0
- private var dispatcher = OnBackPressedDispatcher {
- fallbackCount++
- }
+ private var dispatcher = OnBackPressedDispatcher { fallbackCount++ }
override val onBackPressedDispatcher: OnBackPressedDispatcher
get() = dispatcher
}
diff --git a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/ReportDrawnTest.kt b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/ReportDrawnTest.kt
index db1fee8..8231be3 100644
--- a/activity/activity-compose/src/androidTest/java/androidx/activity/compose/ReportDrawnTest.kt
+++ b/activity/activity-compose/src/androidTest/java/androidx/activity/compose/ReportDrawnTest.kt
@@ -36,8 +36,7 @@
@MediumTest
@RunWith(AndroidJUnit4::class)
class ReportDrawnTest {
- @get:Rule
- val rule = createAndroidComposeRule<TestActivity>()
+ @get:Rule val rule = createAndroidComposeRule<TestActivity>()
@Test
fun testReportFullyDrawnWhen() {
@@ -82,7 +81,7 @@
recomposeInt.value
ReportDrawnAfter {
lockChecks++
- mutex.withLock { }
+ mutex.withLock {}
}
}
@@ -114,12 +113,8 @@
val mutex = Mutex(locked = true)
var conditionReady by mutableStateOf(false)
rule.setContent {
- ReportDrawnWhen {
- conditionReady
- }
- ReportDrawnAfter {
- mutex.withLock { }
- }
+ ReportDrawnWhen { conditionReady }
+ ReportDrawnAfter { mutex.withLock {} }
}
rule.waitForIdle()
@@ -134,9 +129,7 @@
// Should complete as soon as the coroutine is scheduled, which is on the UI thread.
// We just need to wait our turn for the UI thread:
- rule.runOnIdle {
- assertThat(rule.activity.reportFullyDrawnCalled).isTrue()
- }
+ rule.runOnIdle { assertThat(rule.activity.reportFullyDrawnCalled).isTrue() }
}
// same as above, but the order is swapped
@@ -145,12 +138,8 @@
val mutex = Mutex(locked = true)
var conditionReady by mutableStateOf(false)
rule.setContent {
- ReportDrawnWhen {
- conditionReady
- }
- ReportDrawnAfter {
- mutex.withLock { }
- }
+ ReportDrawnWhen { conditionReady }
+ ReportDrawnAfter { mutex.withLock {} }
}
rule.waitForIdle()
@@ -160,9 +149,7 @@
// Should complete as soon as the coroutine is scheduled, which is on the UI thread.
// We just need to wait our turn for the UI thread:
- rule.runOnIdle {
- assertThat(rule.activity.reportFullyDrawnCalled).isFalse()
- }
+ rule.runOnIdle { assertThat(rule.activity.reportFullyDrawnCalled).isFalse() }
conditionReady = true
rule.waitForIdle()
@@ -175,24 +162,18 @@
val mutex = Mutex(locked = true)
var conditionReady by mutableStateOf(false)
rule.setContent {
- AndroidView(factory = { context ->
- ComposeView(context).apply {
- setContent {
- ReportDrawnWhen {
- conditionReady
- }
+ AndroidView(
+ factory = { context ->
+ ComposeView(context).apply { setContent { ReportDrawnWhen { conditionReady } } }
+ }
+ )
+ AndroidView(
+ factory = { context ->
+ ComposeView(context).apply {
+ setContent { ReportDrawnAfter { mutex.withLock {} } }
}
}
- })
- AndroidView(factory = { context ->
- ComposeView(context).apply {
- setContent {
- ReportDrawnAfter {
- mutex.withLock { }
- }
- }
- }
- })
+ )
}
rule.waitForIdle()
@@ -200,9 +181,7 @@
mutex.unlock()
- rule.runOnIdle {
- assertThat(rule.activity.reportFullyDrawnCalled).isFalse()
- }
+ rule.runOnIdle { assertThat(rule.activity.reportFullyDrawnCalled).isFalse() }
conditionReady = true
rule.waitForIdle()
@@ -212,9 +191,7 @@
@Test
fun reportAfterComposition() {
- rule.setContent {
- ReportDrawn()
- }
+ rule.setContent { ReportDrawn() }
rule.waitForIdle()
assertThat(rule.activity.reportFullyDrawnCalled).isTrue()
@@ -227,13 +204,9 @@
var useCondition2 by mutableStateOf(true)
rule.setContent {
- ReportDrawnWhen {
- condition1
- }
+ ReportDrawnWhen { condition1 }
if (useCondition2) {
- ReportDrawnWhen {
- condition2
- }
+ ReportDrawnWhen { condition2 }
}
}
@@ -251,10 +224,11 @@
@Test
fun provideFullyDrawnReporter() {
- val fullyDrawnReporterOwner = object : FullyDrawnReporterOwner {
- override val fullyDrawnReporter: FullyDrawnReporter
- get() = rule.activity.fullyDrawnReporter
- }
+ val fullyDrawnReporterOwner =
+ object : FullyDrawnReporterOwner {
+ override val fullyDrawnReporter: FullyDrawnReporter
+ get() = rule.activity.fullyDrawnReporter
+ }
lateinit var localValue: FullyDrawnReporterOwner
rule.setContent {
CompositionLocalProvider(
diff --git a/activity/activity-compose/src/main/java/androidx/activity/compose/ActivityResultRegistry.kt b/activity/activity-compose/src/main/java/androidx/activity/compose/ActivityResultRegistry.kt
index f458e21..ee8c3f5 100644
--- a/activity/activity-compose/src/main/java/androidx/activity/compose/ActivityResultRegistry.kt
+++ b/activity/activity-compose/src/main/java/androidx/activity/compose/ActivityResultRegistry.kt
@@ -40,30 +40,31 @@
private val LocalComposition = compositionLocalOf<ActivityResultRegistryOwner?> { null }
/**
- * Returns current composition local value for the owner or `null` if one has not
- * been provided nor is one available by looking at the [LocalContext].
+ * Returns current composition local value for the owner or `null` if one has not been provided
+ * nor is one available by looking at the [LocalContext].
*/
public val current: ActivityResultRegistryOwner?
@Composable
- get() = LocalComposition.current
- ?: findOwner<ActivityResultRegistryOwner>(LocalContext.current)
+ get() =
+ LocalComposition.current ?: findOwner<ActivityResultRegistryOwner>(LocalContext.current)
/**
* Associates a [LocalActivityResultRegistryOwner] key to a value in a call to
* [CompositionLocalProvider].
*/
- public infix fun provides(registryOwner: ActivityResultRegistryOwner):
- ProvidedValue<ActivityResultRegistryOwner?> {
- return LocalComposition.provides(registryOwner)
- }
+ public infix fun provides(
+ registryOwner: ActivityResultRegistryOwner
+ ): ProvidedValue<ActivityResultRegistryOwner?> {
+ return LocalComposition.provides(registryOwner)
+ }
}
/**
- * Register a request to [Activity#startActivityForResult][start an activity for result],
- * designated by the given [ActivityResultContract][contract].
+ * Register a request to [Activity#startActivityForResult][start an activity for result], designated
+ * by the given [ActivityResultContract][contract].
*
- * This creates a record in the [ActivityResultRegistry][registry] associated with this
- * caller, managing request code, as well as conversions to/from [Intent] under the hood.
+ * This creates a record in the [ActivityResultRegistry][registry] associated with this caller,
+ * managing request code, as well as conversions to/from [Intent] under the hood.
*
* This *must* be called unconditionally, as part of initialization path.
*
@@ -73,9 +74,7 @@
* @sample androidx.activity.compose.samples.RememberLauncherForActivityResult
*
* @param contract the contract, specifying conversions to/from [Intent]s
- * @param onResult the callback to be called on the main thread when activity result
- * is available
- *
+ * @param onResult the callback to be called on the main thread when activity result is available
* @return the launcher that can be used to start the activity.
*/
@Composable
@@ -91,37 +90,35 @@
// and consistent across configuration changes
val key = rememberSaveable { UUID.randomUUID().toString() }
- val activityResultRegistry = checkNotNull(LocalActivityResultRegistryOwner.current) {
- "No ActivityResultRegistryOwner was provided via LocalActivityResultRegistryOwner"
- }.activityResultRegistry
+ val activityResultRegistry =
+ checkNotNull(LocalActivityResultRegistryOwner.current) {
+ "No ActivityResultRegistryOwner was provided via LocalActivityResultRegistryOwner"
+ }
+ .activityResultRegistry
val realLauncher = remember { ActivityResultLauncherHolder<I>() }
- val returnedLauncher = remember {
- ManagedActivityResultLauncher(realLauncher, currentContract)
- }
+ val returnedLauncher = remember { ManagedActivityResultLauncher(realLauncher, currentContract) }
// DisposableEffect ensures that we only register once
// and that we unregister when the composable is disposed
DisposableEffect(activityResultRegistry, key, contract) {
- realLauncher.launcher = activityResultRegistry.register(key, contract) {
- currentOnResult.value(it)
- }
- onDispose {
- realLauncher.unregister()
- }
+ realLauncher.launcher =
+ activityResultRegistry.register(key, contract) { currentOnResult.value(it) }
+ onDispose { realLauncher.unregister() }
}
return returnedLauncher
}
/**
- * A launcher for a previously-[prepared call][ActivityResultCaller.registerForActivityResult]
- * to start the process of executing an [ActivityResultContract].
+ * A launcher for a previously-[prepared call][ActivityResultCaller.registerForActivityResult] to
+ * start the process of executing an [ActivityResultContract].
*
* This launcher does not support the [unregister] function. Attempting to use [unregister] will
* result in an [IllegalStateException].
*
* @param I type of the input required to launch
*/
-public class ManagedActivityResultLauncher<I, O> internal constructor(
+public class ManagedActivityResultLauncher<I, O>
+internal constructor(
private val launcher: ActivityResultLauncherHolder<I>,
private val currentContract: State<ActivityResultContract<I, O>>
) : ActivityResultLauncher<I>() {
diff --git a/activity/activity-compose/src/main/java/androidx/activity/compose/BackHandler.kt b/activity/activity-compose/src/main/java/androidx/activity/compose/BackHandler.kt
index 588877e..f66d478 100644
--- a/activity/activity-compose/src/main/java/androidx/activity/compose/BackHandler.kt
+++ b/activity/activity-compose/src/main/java/androidx/activity/compose/BackHandler.kt
@@ -41,25 +41,26 @@
compositionLocalOf<OnBackPressedDispatcherOwner?> { null }
/**
- * Returns current composition local value for the owner or `null` if one has not
- * been provided, one has not been set via
- * [androidx.activity.setViewTreeOnBackPressedDispatcherOwner], nor is one available by
- * looking at the [LocalContext].
+ * Returns current composition local value for the owner or `null` if one has not been provided,
+ * one has not been set via [androidx.activity.setViewTreeOnBackPressedDispatcherOwner], nor is
+ * one available by looking at the [LocalContext].
*/
public val current: OnBackPressedDispatcherOwner?
@Composable
- get() = LocalOnBackPressedDispatcherOwner.current
- ?: LocalView.current.findViewTreeOnBackPressedDispatcherOwner()
- ?: findOwner<OnBackPressedDispatcherOwner>(LocalContext.current)
+ get() =
+ LocalOnBackPressedDispatcherOwner.current
+ ?: LocalView.current.findViewTreeOnBackPressedDispatcherOwner()
+ ?: findOwner<OnBackPressedDispatcherOwner>(LocalContext.current)
/**
* Associates a [LocalOnBackPressedDispatcherOwner] key to a value in a call to
* [CompositionLocalProvider].
*/
- public infix fun provides(dispatcherOwner: OnBackPressedDispatcherOwner):
- ProvidedValue<OnBackPressedDispatcherOwner?> {
- return LocalOnBackPressedDispatcherOwner.provides(dispatcherOwner)
- }
+ public infix fun provides(
+ dispatcherOwner: OnBackPressedDispatcherOwner
+ ): ProvidedValue<OnBackPressedDispatcherOwner?> {
+ return LocalOnBackPressedDispatcherOwner.provides(dispatcherOwner)
+ }
}
/**
@@ -68,9 +69,9 @@
* Calling this in your composable adds the given lambda to the [OnBackPressedDispatcher] of the
* [LocalOnBackPressedDispatcherOwner].
*
- * If this is called by nested composables, if enabled, the inner most composable will consume
- * the call to system back and invoke its lambda. The call will continue to propagate up until it
- * finds an enabled BackHandler.
+ * If this is called by nested composables, if enabled, the inner most composable will consume the
+ * call to system back and invoke its lambda. The call will continue to propagate up until it finds
+ * an enabled BackHandler.
*
* @sample androidx.activity.compose.samples.BackHandler
*
@@ -91,20 +92,18 @@
}
}
// On every successful composition, update the callback with the `enabled` value
- SideEffect {
- backCallback.isEnabled = enabled
- }
- val backDispatcher = checkNotNull(LocalOnBackPressedDispatcherOwner.current) {
- "No OnBackPressedDispatcherOwner was provided via LocalOnBackPressedDispatcherOwner"
- }.onBackPressedDispatcher
+ SideEffect { backCallback.isEnabled = enabled }
+ val backDispatcher =
+ checkNotNull(LocalOnBackPressedDispatcherOwner.current) {
+ "No OnBackPressedDispatcherOwner was provided via LocalOnBackPressedDispatcherOwner"
+ }
+ .onBackPressedDispatcher
@Suppress("deprecation", "KotlinRedundantDiagnosticSuppress") // TODO b/330570365
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, backDispatcher) {
// Add callback to the backDispatcher
backDispatcher.addCallback(lifecycleOwner, backCallback)
// When the effect leaves the Composition, remove the callback
- onDispose {
- backCallback.remove()
- }
+ onDispose { backCallback.remove() }
}
}
diff --git a/activity/activity-compose/src/main/java/androidx/activity/compose/ComponentActivity.kt b/activity/activity-compose/src/main/java/androidx/activity/compose/ComponentActivity.kt
index b856a6f..bc5f896 100644
--- a/activity/activity-compose/src/main/java/androidx/activity/compose/ComponentActivity.kt
+++ b/activity/activity-compose/src/main/java/androidx/activity/compose/ComponentActivity.kt
@@ -29,12 +29,11 @@
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
/**
- * Composes the given composable into the given activity. The [content] will become the root view
- * of the given activity.
+ * Composes the given composable into the given activity. The [content] will become the root view of
+ * the given activity.
*
* This is roughly equivalent to calling [ComponentActivity.setContentView] with a [ComposeView]
* i.e.:
- *
* ```
* setContentView(
* ComposeView(this).apply {
@@ -52,29 +51,30 @@
parent: CompositionContext? = null,
content: @Composable () -> Unit
) {
- val existingComposeView = window.decorView
- .findViewById<ViewGroup>(android.R.id.content)
- .getChildAt(0) as? ComposeView
+ val existingComposeView =
+ window.decorView.findViewById<ViewGroup>(android.R.id.content).getChildAt(0) as? ComposeView
- if (existingComposeView != null) with(existingComposeView) {
- setParentCompositionContext(parent)
- setContent(content)
- } else ComposeView(this).apply {
- // Set content and parent **before** setContentView
- // to have ComposeView create the composition on attach
- setParentCompositionContext(parent)
- setContent(content)
- // Set the view tree owners before setting the content view so that the inflation process
- // and attach listeners will see them already present
- setOwners()
- setContentView(this, DefaultActivityContentLayoutParams)
- }
+ if (existingComposeView != null)
+ with(existingComposeView) {
+ setParentCompositionContext(parent)
+ setContent(content)
+ }
+ else
+ ComposeView(this).apply {
+ // Set content and parent **before** setContentView
+ // to have ComposeView create the composition on attach
+ setParentCompositionContext(parent)
+ setContent(content)
+ // Set the view tree owners before setting the content view so that the inflation
+ // process
+ // and attach listeners will see them already present
+ setOwners()
+ setContentView(this, DefaultActivityContentLayoutParams)
+ }
}
-private val DefaultActivityContentLayoutParams = ViewGroup.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT
-)
+private val DefaultActivityContentLayoutParams =
+ ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
/**
* These owners are not set before AppCompat 1.3+ due to a bug, so we need to set them manually in
diff --git a/activity/activity-compose/src/main/java/androidx/activity/compose/PredictiveBackHandler.kt b/activity/activity-compose/src/main/java/androidx/activity/compose/PredictiveBackHandler.kt
index 6a665a7..f7c4e53 100644
--- a/activity/activity-compose/src/main/java/androidx/activity/compose/PredictiveBackHandler.kt
+++ b/activity/activity-compose/src/main/java/androidx/activity/compose/PredictiveBackHandler.kt
@@ -42,9 +42,8 @@
*
* Calling this in your composable adds the given lambda to the [OnBackPressedDispatcher] of the
* [LocalOnBackPressedDispatcherOwner]. The lambda passes in a Flow<BackEventCompat> where each
- * [BackEventCompat] reflects the progress of current gesture back. The lambda content should
- * follow this structure:
- *
+ * [BackEventCompat] reflects the progress of current gesture back. The lambda content should follow
+ * this structure:
* ```
* PredictiveBackHandler { progress: Flow<BackEventCompat> ->
* // code for gesture back started
@@ -59,9 +58,9 @@
* }
* ```
*
- * If this is called by nested composables, if enabled, the inner most composable will consume
- * the call to system back and invoke its lambda. The call will continue to propagate up until it
- * finds an enabled BackHandler.
+ * If this is called by nested composables, if enabled, the inner most composable will consume the
+ * call to system back and invoke its lambda. The call will continue to propagate up until it finds
+ * an enabled BackHandler.
*
* @sample androidx.activity.compose.samples.PredictiveBack
*
@@ -71,8 +70,9 @@
@Composable
public fun PredictiveBackHandler(
enabled: Boolean = true,
- onBack: suspend (progress: @JvmSuppressWildcards Flow<BackEventCompat>) ->
- @JvmSuppressWildcards Unit
+ onBack:
+ suspend (progress: @JvmSuppressWildcards Flow<BackEventCompat>) -> @JvmSuppressWildcards
+ Unit
) {
// ensure we don't re-register callbacks when onBack changes
val currentOnBack by rememberUpdatedState(onBack)
@@ -124,13 +124,13 @@
}
}
- LaunchedEffect(enabled) {
- backCallBack.isEnabled = enabled
- }
+ LaunchedEffect(enabled) { backCallBack.isEnabled = enabled }
- val backDispatcher = checkNotNull(LocalOnBackPressedDispatcherOwner.current) {
- "No OnBackPressedDispatcherOwner was provided via LocalOnBackPressedDispatcherOwner"
- }.onBackPressedDispatcher
+ val backDispatcher =
+ checkNotNull(LocalOnBackPressedDispatcherOwner.current) {
+ "No OnBackPressedDispatcherOwner was provided via LocalOnBackPressedDispatcherOwner"
+ }
+ .onBackPressedDispatcher
@Suppress("deprecation", "KotlinRedundantDiagnosticSuppress") // TODO b/330570365
val lifecycleOwner = LocalLifecycleOwner.current
@@ -138,9 +138,7 @@
DisposableEffect(lifecycleOwner, backDispatcher) {
backDispatcher.addCallback(lifecycleOwner, backCallBack)
- onDispose {
- backCallBack.remove()
- }
+ onDispose { backCallBack.remove() }
}
}
@@ -150,15 +148,12 @@
onBack: suspend (progress: Flow<BackEventCompat>) -> Unit,
) {
val channel = Channel<BackEventCompat>(capacity = BUFFERED, onBufferOverflow = SUSPEND)
- val job = scope.launch {
- var completed = false
- onBack(channel.consumeAsFlow().onCompletion {
- completed = true
- })
- check(completed) {
- "You must collect the progress flow"
+ val job =
+ scope.launch {
+ var completed = false
+ onBack(channel.consumeAsFlow().onCompletion { completed = true })
+ check(completed) { "You must collect the progress flow" }
}
- }
fun send(backEvent: BackEventCompat) = channel.trySend(backEvent)
diff --git a/activity/activity-compose/src/main/java/androidx/activity/compose/ReportDrawn.kt b/activity/activity-compose/src/main/java/androidx/activity/compose/ReportDrawn.kt
index cfefa9c..946bf6a 100644
--- a/activity/activity-compose/src/main/java/androidx/activity/compose/ReportDrawn.kt
+++ b/activity/activity-compose/src/main/java/androidx/activity/compose/ReportDrawn.kt
@@ -29,23 +29,16 @@
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
-/**
- * Manages the composition callback for [ReportDrawnWhen].
- */
+/** Manages the composition callback for [ReportDrawnWhen]. */
private class ReportDrawnComposition(
private val fullyDrawnReporter: FullyDrawnReporter,
private val predicate: () -> Boolean
) : () -> Unit {
- private val snapshotStateObserver = SnapshotStateObserver { command ->
- command()
- }.apply {
- start()
- }
+ private val snapshotStateObserver =
+ SnapshotStateObserver { command -> command() }.apply { start() }
- /**
- * Called whenever the values read in the lambda parameter has changed.
- */
+ /** Called whenever the values read in the lambda parameter has changed. */
private val checkReporter: (() -> Boolean) -> Unit = ::observeReporter
init {
@@ -57,17 +50,15 @@
}
/**
- * Called when the [FullyDrawnReporter] has called [Activity.reportFullyDrawn]. This
- * stops watching for changes to the snapshot.
+ * Called when the [FullyDrawnReporter] has called [Activity.reportFullyDrawn]. This stops
+ * watching for changes to the snapshot.
*/
override fun invoke() {
snapshotStateObserver.clear()
snapshotStateObserver.stop()
}
- /**
- * Stops observing [predicate] and marks the [fullyDrawnReporter] as ready for it.
- */
+ /** Stops observing [predicate] and marks the [fullyDrawnReporter] as ready for it. */
fun removeReporter() {
snapshotStateObserver.clear(predicate)
if (!fullyDrawnReporter.isFullyDrawnReported) {
@@ -92,52 +83,45 @@
* [androidx.activity.ComponentActivity].
*/
object LocalFullyDrawnReporterOwner {
- private val LocalFullyDrawnReporterOwner =
- compositionLocalOf<FullyDrawnReporterOwner?> { null }
+ private val LocalFullyDrawnReporterOwner = compositionLocalOf<FullyDrawnReporterOwner?> { null }
/**
- * Returns current composition local value for the owner or `null` if one has not
- * been provided, one has not been set via
- * [androidx.activity.setViewTreeFullyDrawnReporterOwner], nor is one available by
- * looking at the [LocalContext].
+ * Returns current composition local value for the owner or `null` if one has not been provided,
+ * one has not been set via [androidx.activity.setViewTreeFullyDrawnReporterOwner], nor is one
+ * available by looking at the [LocalContext].
*/
val current: FullyDrawnReporterOwner?
@Composable
- get() = LocalFullyDrawnReporterOwner.current
- ?: LocalView.current.findViewTreeFullyDrawnReporterOwner()
- ?: findOwner<FullyDrawnReporterOwner>(LocalContext.current)
+ get() =
+ LocalFullyDrawnReporterOwner.current
+ ?: LocalView.current.findViewTreeFullyDrawnReporterOwner()
+ ?: findOwner<FullyDrawnReporterOwner>(LocalContext.current)
- /**
- * Associates a [LocalFullyDrawnReporterOwner] key to a value.
- */
- infix fun provides(fullyDrawnReporterOwner: FullyDrawnReporterOwner):
- ProvidedValue<FullyDrawnReporterOwner?> {
+ /** Associates a [LocalFullyDrawnReporterOwner] key to a value. */
+ infix fun provides(
+ fullyDrawnReporterOwner: FullyDrawnReporterOwner
+ ): ProvidedValue<FullyDrawnReporterOwner?> {
return LocalFullyDrawnReporterOwner.provides(fullyDrawnReporterOwner)
}
}
/**
- * Adds [predicate] to the conditions that must be met prior to [Activity.reportFullyDrawn]
- * being called.
+ * Adds [predicate] to the conditions that must be met prior to [Activity.reportFullyDrawn] being
+ * called.
*
* The [Activity] used is extracted from the [LocalView]'s context.
*
* @sample androidx.activity.compose.samples.ReportDrawnWhenSample
*/
@Composable
-fun ReportDrawnWhen(
- predicate: () -> Boolean
-) {
- val fullyDrawnReporter =
- LocalFullyDrawnReporterOwner.current?.fullyDrawnReporter ?: return
+fun ReportDrawnWhen(predicate: () -> Boolean) {
+ val fullyDrawnReporter = LocalFullyDrawnReporterOwner.current?.fullyDrawnReporter ?: return
DisposableEffect(fullyDrawnReporter, predicate) {
if (fullyDrawnReporter.isFullyDrawnReported) {
onDispose {}
} else {
val compositionDrawn = ReportDrawnComposition(fullyDrawnReporter, predicate)
- onDispose {
- compositionDrawn.removeReporter()
- }
+ onDispose { compositionDrawn.removeReporter() }
}
}
}
@@ -149,12 +133,10 @@
*
* @sample androidx.activity.compose.samples.ReportDrawnSample
*/
-@Composable
-fun ReportDrawn() = ReportDrawnWhen { true }
+@Composable fun ReportDrawn() = ReportDrawnWhen { true }
/**
- * Adds [block] to the methods that must complete prior to [Activity.reportFullyDrawn]
- * being called.
+ * Adds [block] to the methods that must complete prior to [Activity.reportFullyDrawn] being called.
*
* The [Activity] used is extracted from the [LocalView]'s context.
*
@@ -164,12 +146,7 @@
* @sample androidx.activity.compose.samples.ReportDrawnAfterSample
*/
@Composable
-fun ReportDrawnAfter(
- block: suspend () -> Unit
-) {
- val fullyDrawnReporter =
- LocalFullyDrawnReporterOwner.current?.fullyDrawnReporter ?: return
- LaunchedEffect(block, fullyDrawnReporter) {
- fullyDrawnReporter.reportWhenComplete(block)
- }
+fun ReportDrawnAfter(block: suspend () -> Unit) {
+ val fullyDrawnReporter = LocalFullyDrawnReporterOwner.current?.fullyDrawnReporter ?: return
+ LaunchedEffect(block, fullyDrawnReporter) { fullyDrawnReporter.reportWhenComplete(block) }
}
diff --git a/activity/activity-lint/src/main/java/androidx/activity/lint/ActivityIssueRegistry.kt b/activity/activity-lint/src/main/java/androidx/activity/lint/ActivityIssueRegistry.kt
index e2022c7..648c984 100644
--- a/activity/activity-lint/src/main/java/androidx/activity/lint/ActivityIssueRegistry.kt
+++ b/activity/activity-lint/src/main/java/androidx/activity/lint/ActivityIssueRegistry.kt
@@ -20,21 +20,19 @@
import com.android.tools.lint.client.api.Vendor
import com.android.tools.lint.detector.api.CURRENT_API
-/**
- * Issue Registry containing Activity specific lint Issues.
- */
+/** Issue Registry containing Activity specific lint Issues. */
@Suppress("UnstableApiUsage")
class ActivityIssueRegistry : IssueRegistry() {
// tests are run with this version. We ensure that with ApiLintVersionsTest
override val api = 14
override val minApi = CURRENT_API
- override val issues get() = listOf(
- ActivityResultFragmentVersionDetector.ISSUE,
- OnBackPressedDetector.ISSUE
- )
- override val vendor = Vendor(
- feedbackUrl = "https://issuetracker.google.com/issues/new?component=527362",
- identifier = "androidx.activity",
- vendorName = "Android Open Source Project",
- )
+ override val issues
+ get() = listOf(ActivityResultFragmentVersionDetector.ISSUE, OnBackPressedDetector.ISSUE)
+
+ override val vendor =
+ Vendor(
+ feedbackUrl = "https://issuetracker.google.com/issues/new?component=527362",
+ identifier = "androidx.activity",
+ vendorName = "Android Open Source Project",
+ )
}
diff --git a/activity/activity-lint/src/main/java/androidx/activity/lint/ActivityResultFragmentVersionDetector.kt b/activity/activity-lint/src/main/java/androidx/activity/lint/ActivityResultFragmentVersionDetector.kt
index 23900a5..f8893dd 100644
--- a/activity/activity-lint/src/main/java/androidx/activity/lint/ActivityResultFragmentVersionDetector.kt
+++ b/activity/activity-lint/src/main/java/androidx/activity/lint/ActivityResultFragmentVersionDetector.kt
@@ -37,23 +37,28 @@
companion object {
const val FRAGMENT_VERSION = "1.3.0"
- val ISSUE = Issue.create(
- id = "InvalidFragmentVersionForActivityResult",
- briefDescription = "Update to Fragment $FRAGMENT_VERSION to use ActivityResult APIs",
- explanation = """In order to use the ActivityResult APIs you must upgrade your \
+ val ISSUE =
+ Issue.create(
+ id = "InvalidFragmentVersionForActivityResult",
+ briefDescription =
+ "Update to Fragment $FRAGMENT_VERSION to use ActivityResult APIs",
+ explanation =
+ """In order to use the ActivityResult APIs you must upgrade your \
Fragment version to $FRAGMENT_VERSION. Previous versions of FragmentActivity \
failed to call super.onRequestPermissionsResult() and used invalid request codes""",
- category = Category.CORRECTNESS,
- severity = Severity.FATAL,
- implementation = Implementation(
- ActivityResultFragmentVersionDetector::class.java,
- EnumSet.of(Scope.JAVA_FILE, Scope.GRADLE_FILE),
- Scope.JAVA_FILE_SCOPE,
- Scope.GRADLE_SCOPE
- )
- ).addMoreInfo(
- "https://developer.android.com/training/permissions/requesting#make-the-request"
- )
+ category = Category.CORRECTNESS,
+ severity = Severity.FATAL,
+ implementation =
+ Implementation(
+ ActivityResultFragmentVersionDetector::class.java,
+ EnumSet.of(Scope.JAVA_FILE, Scope.GRADLE_FILE),
+ Scope.JAVA_FILE_SCOPE,
+ Scope.GRADLE_SCOPE
+ )
+ )
+ .addMoreInfo(
+ "https://developer.android.com/training/permissions/requesting#make-the-request"
+ )
}
var locations = ArrayList<Location>()
@@ -95,32 +100,32 @@
} else if (!checkedImplementationDependencies) {
context.project.buildVariant.mainArtifact.dependencies.getAll().forEach { lmLibrary ->
reportIssue(
- (lmLibrary as? LintModelAndroidLibrary)
- ?.resolvedCoordinates.toString(), context, false
+ (lmLibrary as? LintModelAndroidLibrary)?.resolvedCoordinates.toString(),
+ context,
+ false
)
}
checkedImplementationDependencies = true
}
}
- private fun reportIssue(
- value: String,
- context: GradleContext,
- removeQuotes: Boolean = true
- ) {
- val library = if (removeQuotes) {
- getStringLiteralValue(value)
- } else {
- value
- }
+ private fun reportIssue(value: String, context: GradleContext, removeQuotes: Boolean = true) {
+ val library =
+ if (removeQuotes) {
+ getStringLiteralValue(value)
+ } else {
+ value
+ }
if (library.isNotEmpty()) {
- val currentVersion = library.substringAfter("androidx.fragment:fragment:")
- .substringBeforeLast("-")
+ val currentVersion =
+ library.substringAfter("androidx.fragment:fragment:").substringBeforeLast("-")
if (library != currentVersion && currentVersion < FRAGMENT_VERSION) {
locations.forEach { location ->
context.report(
- ISSUE, expression, location,
+ ISSUE,
+ expression,
+ location,
"Upgrade Fragment version to at least $FRAGMENT_VERSION."
)
}
@@ -134,10 +139,10 @@
* Returns an empty string if [value] is not a string literal.
*/
private fun getStringLiteralValue(value: String): String {
- if (value.length > 2 && (
- value.startsWith("'") && value.endsWith("'") ||
- value.startsWith("\"") && value.endsWith("\"")
- )
+ if (
+ value.length > 2 &&
+ (value.startsWith("'") && value.endsWith("'") ||
+ value.startsWith("\"") && value.endsWith("\""))
) {
return value.substring(1, value.length - 1)
}
diff --git a/activity/activity-lint/src/main/java/androidx/activity/lint/OnBackPressedDetector.kt b/activity/activity-lint/src/main/java/androidx/activity/lint/OnBackPressedDetector.kt
index 7e3b21e..7902c3a 100644
--- a/activity/activity-lint/src/main/java/androidx/activity/lint/OnBackPressedDetector.kt
+++ b/activity/activity-lint/src/main/java/androidx/activity/lint/OnBackPressedDetector.kt
@@ -31,28 +31,30 @@
class OnBackPressedDetector : Detector(), Detector.UastScanner {
companion object {
- val ISSUE = Issue.create(
- id = "InvalidUseOfOnBackPressed",
- briefDescription = "Do not call onBackPressed() within OnBackPressedDisptacher",
- explanation = """You should not used OnBackPressedCallback for non-UI cases. If you
+ val ISSUE =
+ Issue.create(
+ id = "InvalidUseOfOnBackPressed",
+ briefDescription = "Do not call onBackPressed() within OnBackPressedDisptacher",
+ explanation =
+ """You should not used OnBackPressedCallback for non-UI cases. If you
|add a callback, you have to handle back completely in the callback.
""",
- category = Category.CORRECTNESS,
- severity = Severity.WARNING,
- implementation = Implementation(
- OnBackPressedDetector::class.java,
- EnumSet.of(Scope.JAVA_FILE),
- Scope.JAVA_FILE_SCOPE
- )
- ).addMoreInfo(
- "https://developer.android.com/guide/navigation/custom-back/" +
- "predictive-back-gesture#ui-logic"
- )
+ category = Category.CORRECTNESS,
+ severity = Severity.WARNING,
+ implementation =
+ Implementation(
+ OnBackPressedDetector::class.java,
+ EnumSet.of(Scope.JAVA_FILE),
+ Scope.JAVA_FILE_SCOPE
+ )
+ )
+ .addMoreInfo(
+ "https://developer.android.com/guide/navigation/custom-back/" +
+ "predictive-back-gesture#ui-logic"
+ )
}
- override fun getApplicableMethodNames(): List<String> = listOf(
- OnBackPressed
- )
+ override fun getApplicableMethodNames(): List<String> = listOf(OnBackPressed)
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
method.containingClass ?: return
diff --git a/activity/activity-lint/src/test/java/androidx/activity/lint/ActivityResultFragmentVersionDetectorTest.kt b/activity/activity-lint/src/test/java/androidx/activity/lint/ActivityResultFragmentVersionDetectorTest.kt
index cc9312b..961d296 100644
--- a/activity/activity-lint/src/test/java/androidx/activity/lint/ActivityResultFragmentVersionDetectorTest.kt
+++ b/activity/activity-lint/src/test/java/androidx/activity/lint/ActivityResultFragmentVersionDetectorTest.kt
@@ -34,9 +34,10 @@
@Test
fun expectPassRegisterForActivityResult() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -44,25 +45,28 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
"""
- ),
- *STUBS,
- gradle(
- "build.gradle",
- """
+ ),
+ *STUBS,
+ gradle(
+ "build.gradle",
+ """
dependencies {
api("androidx.fragment:fragment:$FRAGMENT_VERSION")
}
"""
- ).indented()
- )
- .run().expectClean()
+ )
+ .indented()
+ )
+ .run()
+ .expectClean()
}
@Test
fun expectPassRegisterForActivityResultStableVersions() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -70,25 +74,28 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
"""
- ),
- *STUBS,
- gradle(
- "build.gradle",
- """
+ ),
+ *STUBS,
+ gradle(
+ "build.gradle",
+ """
dependencies {
api("androidx.fragment:fragment:1.3.1")
}
"""
- ).indented()
- )
- .run().expectClean()
+ )
+ .indented()
+ )
+ .run()
+ .expectClean()
}
@Test
fun expectPassNewerStableVersion() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -96,24 +103,28 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
"""
- ),
- *STUBS,
- gradle(
- "build.gradle",
- """
+ ),
+ *STUBS,
+ gradle(
+ "build.gradle",
+ """
dependencies {
api("androidx.fragment:fragment:1.4.0")
}
"""
- ).indented()
- ).run().expectClean()
+ )
+ .indented()
+ )
+ .run()
+ .expectClean()
}
@Test
fun expectPassNewerSnapshotVersions() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -121,24 +132,28 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
"""
- ),
- *STUBS,
- gradle(
- "build.gradle",
- """
+ ),
+ *STUBS,
+ gradle(
+ "build.gradle",
+ """
dependencies {
api("androidx.fragment:fragment:1.4.0-SNAPSHOT")
}
"""
- ).indented()
- ).run().expectClean()
+ )
+ .indented()
+ )
+ .run()
+ .expectClean()
}
@Test
fun expectPassNewerAlphaVersions() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -146,24 +161,28 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
"""
- ),
- *STUBS,
- gradle(
- "build.gradle",
- """
+ ),
+ *STUBS,
+ gradle(
+ "build.gradle",
+ """
dependencies {
api("androidx.fragment:fragment:1.4.0-alpha01")
}
"""
- ).indented()
- ).run().expectClean()
+ )
+ .indented()
+ )
+ .run()
+ .expectClean()
}
@Test
fun expectPassRegisterForActivityResultProject() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -171,33 +190,36 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
"""
- ),
- *STUBS,
- gradle(
- "build.gradle",
- """
+ ),
+ *STUBS,
+ gradle(
+ "build.gradle",
+ """
dependencies {
implementation(project(":fragment:fragment-ktx"))
}
"""
- ).indented()
- )
- .run().expectClean()
+ )
+ .indented()
+ )
+ .run()
+ .expectClean()
}
@Test
fun expectFailRegisterForActivityResult() {
- lint().files(
- gradle(
- """
+ lint()
+ .files(
+ gradle(
+ """
dependencies {
api("androidx.fragment:fragment:1.2.4")
}
"""
- ),
- *STUBS,
- kotlin(
- """
+ ),
+ *STUBS,
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -205,8 +227,9 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
"""
- ).indented()
- )
+ )
+ .indented()
+ )
.run()
.expect(
"""
@@ -214,23 +237,25 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
- """.trimIndent()
+ """
+ .trimIndent()
)
}
@Test
fun expectFailRegisterForActivityResultInMethod() {
- lint().files(
- gradle(
- """
+ lint()
+ .files(
+ gradle(
+ """
dependencies {
api("androidx.fragment:fragment:1.2.4")
}
"""
- ),
- *STUBS,
- kotlin(
- """
+ ),
+ *STUBS,
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -242,8 +267,9 @@
launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
}
"""
- ).indented()
- )
+ )
+ .indented()
+ )
.run()
.expect(
"""
@@ -251,23 +277,25 @@
launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
- """.trimIndent()
+ """
+ .trimIndent()
)
}
@Test
fun expectFailRegisterForActivityResultMultipleCalls() {
- lint().files(
- gradle(
- """
+ lint()
+ .files(
+ gradle(
+ """
dependencies {
api("androidx.fragment:fragment:1.2.4")
}
"""
- ),
- *STUBS,
- kotlin(
- """
+ ),
+ *STUBS,
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -281,8 +309,9 @@
launcher2 = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
}
"""
- ).indented()
- )
+ )
+ .indented()
+ )
.run()
.expect(
"""
@@ -293,15 +322,17 @@
launcher2 = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 errors, 0 warnings
- """.trimIndent()
+ """
+ .trimIndent()
)
}
@Test
fun expectFailTransitiveDependency() {
- val projectFragment = project(
- kotlin(
- """
+ val projectFragment =
+ project(
+ kotlin(
+ """
package com.example
import androidx.activity.result.ActivityResultCaller
@@ -309,30 +340,37 @@
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
"""
- ),
- *STUBS,
- gradle(
- "build.gradle",
- """
+ ),
+ *STUBS,
+ gradle(
+ "build.gradle",
+ """
dependencies {
implementation("androidx.fragment:fragment-ktx:1.2.4")
}
"""
- ).indented()
- ).withDependencyGraph(
- """
+ )
+ .indented()
+ )
+ .withDependencyGraph(
+ """
+--- androidx.fragment:fragment-ktx:1.2.4
\--- androidx.fragment:fragment:1.2.4
- """.trimIndent()
- )
-
- lint().projects(projectFragment).run().expect(
"""
+ .trimIndent()
+ )
+
+ lint()
+ .projects(projectFragment)
+ .run()
+ .expect(
+ """
src/main/kotlin/com/example/test.kt:7: Error: Upgrade Fragment version to at least $FRAGMENT_VERSION. [InvalidFragmentVersionForActivityResult]
val launcher = ActivityResultCaller().registerForActivityResult(ActivityResultContract())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
- """.trimIndent()
- )
+ """
+ .trimIndent()
+ )
}
}
diff --git a/activity/activity-lint/src/test/java/androidx/activity/lint/OnBackPressedDispatcherTest.kt b/activity/activity-lint/src/test/java/androidx/activity/lint/OnBackPressedDispatcherTest.kt
index 9c903c2..10aa075 100644
--- a/activity/activity-lint/src/test/java/androidx/activity/lint/OnBackPressedDispatcherTest.kt
+++ b/activity/activity-lint/src/test/java/androidx/activity/lint/OnBackPressedDispatcherTest.kt
@@ -28,14 +28,14 @@
class OnBackPressedDispatcherTest : LintDetectorTest() {
override fun getDetector(): Detector = OnBackPressedDetector()
- override fun getIssues(): MutableList<Issue> =
- mutableListOf(OnBackPressedDetector.ISSUE)
+ override fun getIssues(): MutableList<Issue> = mutableListOf(OnBackPressedDetector.ISSUE)
@Test
fun expectPassOnBackPressed() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.activity.ComponentActivity
@@ -48,17 +48,19 @@
dispatcher.onBackPressed()
}
"""
- ),
- *STUBS
- )
- .run().expectClean()
+ ),
+ *STUBS
+ )
+ .run()
+ .expectClean()
}
@Test
fun expectFailOnBackPressed() {
- lint().files(
- kotlin(
- """
+ lint()
+ .files(
+ kotlin(
+ """
package com.example
import androidx.activity.ComponentActivity
@@ -76,9 +78,9 @@
}
}
"""
- ),
- *STUBS
- )
+ ),
+ *STUBS
+ )
.run()
.expect(
"""
diff --git a/activity/activity-lint/src/test/java/androidx/activity/lint/stubs/Stubs.kt b/activity/activity-lint/src/test/java/androidx/activity/lint/stubs/Stubs.kt
index caf6b3c..adafa59 100644
--- a/activity/activity-lint/src/test/java/androidx/activity/lint/stubs/Stubs.kt
+++ b/activity/activity-lint/src/test/java/androidx/activity/lint/stubs/Stubs.kt
@@ -19,59 +19,65 @@
import com.android.tools.lint.checks.infrastructure.LintDetectorTest.java
import com.android.tools.lint.checks.infrastructure.LintDetectorTest.kotlin
-private val ACTIVITY_RESULT_CALLER = java(
- """
+private val ACTIVITY_RESULT_CALLER =
+ java(
+ """
package androidx.activity.result;
public class ActivityResultCaller {
public ActivityResultLauncher registerForActivityResult(ActivityResultContract contract) {}
}
"""
-)
+ )
-private val ACTIVITY_RESULT_CONTRACT = java(
- """
+private val ACTIVITY_RESULT_CONTRACT =
+ java(
+ """
package androidx.activity.result.contract;
public class ActivityResultContract { }
"""
-)
+ )
-private val COMPONENT_ACTIVITY = kotlin(
- """
+private val COMPONENT_ACTIVITY =
+ kotlin(
+ """
package androidx.activity
class ComponentActivity {
open fun onBackPressed() { }
}
"""
-)
+ )
-private val ON_BACK_PRESSED_CALLBACK = kotlin(
- """
+private val ON_BACK_PRESSED_CALLBACK =
+ kotlin(
+ """
package androidx.activity
class OnBackPressedCallback {
open fun handleOnBackPressed() { }
}
"""
-)
+ )
-private val ON_BACK_PRESSED_DISPATCHER = kotlin(
- """
+private val ON_BACK_PRESSED_DISPATCHER =
+ kotlin(
+ """
package androidx.activity
class OnBackPressedDispatcher {
open fun onBackPressed() { }
}
"""
-)
+ )
// stubs for testing calls to registerForActivityResult
-internal val STUBS = arrayOf(
- ACTIVITY_RESULT_CALLER,
- ACTIVITY_RESULT_CONTRACT,
- COMPONENT_ACTIVITY,
- ON_BACK_PRESSED_CALLBACK,
- ON_BACK_PRESSED_DISPATCHER
-)
+internal val STUBS =
+ arrayOf(
+ ACTIVITY_RESULT_CALLER,
+ ACTIVITY_RESULT_CONTRACT,
+ COMPONENT_ACTIVITY,
+ ON_BACK_PRESSED_CALLBACK,
+ ON_BACK_PRESSED_DISPATCHER
+ )
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ActivityViewModelLazyTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ActivityViewModelLazyTest.kt
index 6601b128..7c4c16a 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ActivityViewModelLazyTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ActivityViewModelLazyTest.kt
@@ -35,12 +35,12 @@
@MediumTest
class ActivityViewModelLazyTest {
@Suppress("DEPRECATION")
- @get:Rule val activityRule = androidx.test.rule.ActivityTestRule<TestActivity>(
- TestActivity::class.java
- )
+ @get:Rule
+ val activityRule = androidx.test.rule.ActivityTestRule<TestActivity>(TestActivity::class.java)
@UiThreadTest
- @Test fun vmInitialization() {
+ @Test
+ fun vmInitialization() {
val activity = activityRule.activity
assertThat(activity.vm).isNotNull()
assertThat(activity.factoryVM.prop).isEqualTo("activity")
@@ -53,9 +53,8 @@
val factoryVM: TestFactorizedViewModel by viewModels { VMFactory("activity") }
lateinit var injectedFactory: ViewModelProvider.Factory
val daggerPoorCopyVM: TestDaggerViewModel by viewModels { injectedFactory }
- val savedStateViewModel: TestSavedStateViewModel by viewModels(
- extrasProducer = { defaultViewModelCreationExtras }
- )
+ val savedStateViewModel: TestSavedStateViewModel by
+ viewModels(extrasProducer = { defaultViewModelCreationExtras })
override fun onCreate(savedInstanceState: Bundle?) {
injectedFactory = VMFactory("dagger")
@@ -74,8 +73,11 @@
}
class TestViewModel : ViewModel()
+
class TestFactorizedViewModel(val prop: String) : ViewModel()
+
class TestDaggerViewModel(val prop: String) : ViewModel()
+
class TestSavedStateViewModel(val savedStateHandle: SavedStateHandle) : ViewModel() {
val defaultValue = savedStateHandle.get<String>("test")
}
@@ -87,7 +89,8 @@
modelClass == TestFactorizedViewModel::class.java -> TestFactorizedViewModel(prop)
modelClass == TestDaggerViewModel::class.java -> TestDaggerViewModel(prop)
else -> throw IllegalArgumentException()
- } as T
+ }
+ as T
}
}
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityCallbacksTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityCallbacksTest.kt
index 039e19d..21861e3 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityCallbacksTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityCallbacksTest.kt
@@ -39,20 +39,16 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivityCallbacksTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun onConfigurationChanged() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
- var receivedFontScale = withActivity {
- resources.configuration.fontScale
- }
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ var receivedFontScale = withActivity { resources.configuration.fontScale }
val expectedFontScale = receivedFontScale * 2
- val listener = Consumer<Configuration> { newConfig ->
- receivedFontScale = newConfig.fontScale
- }
+ val listener =
+ Consumer<Configuration> { newConfig -> receivedFontScale = newConfig.fontScale }
withActivity {
addOnConfigurationChangedListener(listener)
val newConfig = Configuration(resources.configuration)
@@ -66,15 +62,12 @@
@Test
fun onConfigurationChangedRemove() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
- var receivedFontScale = withActivity {
- resources.configuration.fontScale
- }
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ var receivedFontScale = withActivity { resources.configuration.fontScale }
val expectedFontScale = receivedFontScale * 2
- val listener = Consumer<Configuration> { newConfig ->
- receivedFontScale = newConfig.fontScale
- }
+ val listener =
+ Consumer<Configuration> { newConfig -> receivedFontScale = newConfig.fontScale }
withActivity {
addOnConfigurationChangedListener(listener)
val newConfig = Configuration(resources.configuration)
@@ -97,24 +90,23 @@
@Test
fun onConfigurationChangedReentrant() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val activity = withActivity { this }
- var receivedFontScale = withActivity {
- resources.configuration.fontScale
- }
+ var receivedFontScale = withActivity { resources.configuration.fontScale }
val expectedFontScale = receivedFontScale * 2
- val listener = object : Consumer<Configuration> {
- override fun accept(value: Configuration) {
- receivedFontScale = value.fontScale
- activity.removeOnConfigurationChangedListener(this)
+ val listener =
+ object : Consumer<Configuration> {
+ override fun accept(value: Configuration) {
+ receivedFontScale = value.fontScale
+ activity.removeOnConfigurationChangedListener(this)
+ }
}
- }
withActivity {
addOnConfigurationChangedListener(listener)
// Add a second listener to force a ConcurrentModificationException
// if not properly handled by ComponentActivity
- addOnConfigurationChangedListener { }
+ addOnConfigurationChangedListener {}
val newConfig = Configuration(resources.configuration)
newConfig.fontScale *= 2
onConfigurationChanged(newConfig)
@@ -131,12 +123,10 @@
@Suppress("DEPRECATION")
@Test
fun onTrimMemory() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
var receivedLevel = -1
- val listener = Consumer<Int> { level ->
- receivedLevel = level
- }
+ val listener = Consumer<Int> { level -> receivedLevel = level }
withActivity {
addOnTrimMemoryListener(listener)
onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE)
@@ -149,12 +139,10 @@
@Suppress("DEPRECATION")
@Test
fun onTrimMemoryRemove() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
var receivedLevel = -1
- val listener = Consumer<Int> { level ->
- receivedLevel = level
- }
+ val listener = Consumer<Int> { level -> receivedLevel = level }
withActivity {
addOnTrimMemoryListener(listener)
onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE)
@@ -175,21 +163,22 @@
@Suppress("DEPRECATION")
@Test
fun onTrimMemoryRemoveReentrant() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val activity = withActivity { this }
var receivedLevel = -1
- val listener = object : Consumer<Int> {
- override fun accept(value: Int) {
- receivedLevel = value
- activity.removeOnTrimMemoryListener(this)
+ val listener =
+ object : Consumer<Int> {
+ override fun accept(value: Int) {
+ receivedLevel = value
+ activity.removeOnTrimMemoryListener(this)
+ }
}
- }
withActivity {
addOnTrimMemoryListener(listener)
// Add a second listener to force a ConcurrentModificationException
// if not properly handled by ComponentActivity
- addOnTrimMemoryListener { }
+ addOnTrimMemoryListener {}
onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE)
onTrimMemory(ComponentCallbacks2.TRIM_MEMORY_COMPLETE)
}
@@ -201,55 +190,45 @@
@Test
fun onNewIntent() {
- withUse(ActivityScenario.launch(SingleTopActivity::class.java)) {
+ withUse(ActivityScenario.launch(SingleTopActivity::class.java)) {
val receivedIntents = mutableListOf<Intent>()
- val listener = Consumer<Intent> { intent ->
- receivedIntents += intent
- }
+ val listener = Consumer<Intent> { intent -> receivedIntents += intent }
withActivity {
addOnNewIntentListener(listener)
- onNewIntent(Intent(this, SingleTopActivity::class.java).apply {
- putExtra("newExtra", 5)
- })
+ onNewIntent(
+ Intent(this, SingleTopActivity::class.java).apply { putExtra("newExtra", 5) }
+ )
}
- assertWithMessage("Should have received one intent")
- .that(receivedIntents)
- .hasSize(1)
+ assertWithMessage("Should have received one intent").that(receivedIntents).hasSize(1)
val receivedIntent = receivedIntents.first()
- assertThat(receivedIntent.getIntExtra("newExtra", -1))
- .isEqualTo(5)
+ assertThat(receivedIntent.getIntExtra("newExtra", -1)).isEqualTo(5)
}
}
@Test
fun onNewIntentRemove() {
- withUse(ActivityScenario.launch(SingleTopActivity::class.java)) {
+ withUse(ActivityScenario.launch(SingleTopActivity::class.java)) {
val receivedIntents = mutableListOf<Intent>()
- val listener = Consumer<Intent> { intent ->
- receivedIntents += intent
- }
+ val listener = Consumer<Intent> { intent -> receivedIntents += intent }
withActivity {
addOnNewIntentListener(listener)
- onNewIntent(Intent(this, SingleTopActivity::class.java).apply {
- putExtra("newExtra", 5)
- })
+ onNewIntent(
+ Intent(this, SingleTopActivity::class.java).apply { putExtra("newExtra", 5) }
+ )
}
- assertWithMessage("Should have received one intent")
- .that(receivedIntents)
- .hasSize(1)
+ assertWithMessage("Should have received one intent").that(receivedIntents).hasSize(1)
val receivedIntent = receivedIntents.first()
- assertThat(receivedIntent.getIntExtra("newExtra", -1))
- .isEqualTo(5)
+ assertThat(receivedIntent.getIntExtra("newExtra", -1)).isEqualTo(5)
withActivity {
removeOnNewIntentListener(listener)
- onNewIntent(Intent(this, SingleTopActivity::class.java).apply {
- putExtra("newExtra", 5)
- })
+ onNewIntent(
+ Intent(this, SingleTopActivity::class.java).apply { putExtra("newExtra", 5) }
+ )
}
assertWithMessage("Should have received only one intent")
@@ -260,27 +239,28 @@
@Test
fun onNewIntentReentrant() {
- withUse(ActivityScenario.launch(SingleTopActivity::class.java)) {
+ withUse(ActivityScenario.launch(SingleTopActivity::class.java)) {
val activity = withActivity { this }
val receivedIntents = mutableListOf<Intent>()
- val listener = object : Consumer<Intent> {
- override fun accept(value: Intent) {
- receivedIntents += value
- activity.removeOnNewIntentListener(this)
+ val listener =
+ object : Consumer<Intent> {
+ override fun accept(value: Intent) {
+ receivedIntents += value
+ activity.removeOnNewIntentListener(this)
+ }
}
- }
withActivity {
addOnNewIntentListener(listener)
// Add a second listener to force a ConcurrentModificationException
// if not properly handled by ComponentActivity
- addOnNewIntentListener { }
- onNewIntent(Intent(this, SingleTopActivity::class.java).apply {
- putExtra("newExtra", 5)
- })
- onNewIntent(Intent(this, SingleTopActivity::class.java).apply {
- putExtra("newExtra", 10)
- })
+ addOnNewIntentListener {}
+ onNewIntent(
+ Intent(this, SingleTopActivity::class.java).apply { putExtra("newExtra", 5) }
+ )
+ onNewIntent(
+ Intent(this, SingleTopActivity::class.java).apply { putExtra("newExtra", 10) }
+ )
}
// Only the first Intent should be received
@@ -288,20 +268,17 @@
.that(receivedIntents)
.hasSize(1)
val receivedIntent = receivedIntents.first()
- assertThat(receivedIntent.getIntExtra("newExtra", -1))
- .isEqualTo(5)
+ assertThat(receivedIntent.getIntExtra("newExtra", -1)).isEqualTo(5)
}
}
@Suppress("DEPRECATION")
@Test
fun onMultiWindowModeChanged() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
lateinit var receivedInfo: MultiWindowModeChangedInfo
- val listener = Consumer<MultiWindowModeChangedInfo> { info ->
- receivedInfo = info
- }
+ val listener = Consumer<MultiWindowModeChangedInfo> { info -> receivedInfo = info }
withActivity {
addOnMultiWindowModeChangedListener(listener)
onMultiWindowModeChanged(true)
@@ -314,14 +291,15 @@
@SdkSuppress(minSdkVersion = 26)
@Test
fun onMultiWindowModeChangedWithConfig() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
lateinit var receivedInfo: MultiWindowModeChangedInfo
var dispatchCount = 0
- val listener = Consumer<MultiWindowModeChangedInfo> { info ->
- receivedInfo = info
- dispatchCount++
- }
+ val listener =
+ Consumer<MultiWindowModeChangedInfo> { info ->
+ receivedInfo = info
+ dispatchCount++
+ }
lateinit var newConfig: Configuration
withActivity {
addOnMultiWindowModeChangedListener(listener)
@@ -338,12 +316,10 @@
@Suppress("DEPRECATION")
@Test
fun onMultiWindowModeChangedRemove() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
lateinit var receivedInfo: MultiWindowModeChangedInfo
- val listener = Consumer<MultiWindowModeChangedInfo> { info ->
- receivedInfo = info
- }
+ val listener = Consumer<MultiWindowModeChangedInfo> { info -> receivedInfo = info }
withActivity {
addOnMultiWindowModeChangedListener(listener)
onMultiWindowModeChanged(true)
@@ -364,21 +340,22 @@
@Suppress("DEPRECATION")
@Test
fun onMultiWindowModeChangedRemoveReentrant() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val activity = withActivity { this }
lateinit var receivedInfo: MultiWindowModeChangedInfo
- val listener = object : Consumer<MultiWindowModeChangedInfo> {
- override fun accept(value: MultiWindowModeChangedInfo) {
- receivedInfo = value
- activity.removeOnMultiWindowModeChangedListener(this)
+ val listener =
+ object : Consumer<MultiWindowModeChangedInfo> {
+ override fun accept(value: MultiWindowModeChangedInfo) {
+ receivedInfo = value
+ activity.removeOnMultiWindowModeChangedListener(this)
+ }
}
- }
withActivity {
addOnMultiWindowModeChangedListener(listener)
// Add a second listener to force a ConcurrentModificationException
// if not properly handled by ComponentActivity
- addOnMultiWindowModeChangedListener { }
+ addOnMultiWindowModeChangedListener {}
onMultiWindowModeChanged(true)
onMultiWindowModeChanged(false)
}
@@ -391,12 +368,10 @@
@Suppress("DEPRECATION")
@Test
fun onPictureInPictureModeChanged() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
lateinit var receivedInfo: PictureInPictureModeChangedInfo
- val listener = Consumer<PictureInPictureModeChangedInfo> { info ->
- receivedInfo = info
- }
+ val listener = Consumer<PictureInPictureModeChangedInfo> { info -> receivedInfo = info }
withActivity {
addOnPictureInPictureModeChangedListener(listener)
onPictureInPictureModeChanged(true)
@@ -409,14 +384,15 @@
@SdkSuppress(minSdkVersion = 26)
@Test
fun onPictureInPictureModeChangedWithConfig() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
lateinit var receivedInfo: PictureInPictureModeChangedInfo
var dispatchCount = 0
- val listener = Consumer<PictureInPictureModeChangedInfo> { info ->
- receivedInfo = info
- dispatchCount++
- }
+ val listener =
+ Consumer<PictureInPictureModeChangedInfo> { info ->
+ receivedInfo = info
+ dispatchCount++
+ }
lateinit var newConfig: Configuration
withActivity {
addOnPictureInPictureModeChangedListener(listener)
@@ -433,12 +409,10 @@
@Suppress("DEPRECATION")
@Test
fun onPictureInPictureModeChangedRemove() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
lateinit var receivedInfo: PictureInPictureModeChangedInfo
- val listener = Consumer<PictureInPictureModeChangedInfo> { info ->
- receivedInfo = info
- }
+ val listener = Consumer<PictureInPictureModeChangedInfo> { info -> receivedInfo = info }
withActivity {
addOnPictureInPictureModeChangedListener(listener)
onPictureInPictureModeChanged(true)
@@ -459,21 +433,22 @@
@Suppress("DEPRECATION")
@Test
fun onPictureInPictureModeChangedRemoveReentrant() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val activity = withActivity { this }
lateinit var receivedInfo: PictureInPictureModeChangedInfo
- val listener = object : Consumer<PictureInPictureModeChangedInfo> {
- override fun accept(value: PictureInPictureModeChangedInfo) {
- receivedInfo = value
- activity.removeOnPictureInPictureModeChangedListener(this)
+ val listener =
+ object : Consumer<PictureInPictureModeChangedInfo> {
+ override fun accept(value: PictureInPictureModeChangedInfo) {
+ receivedInfo = value
+ activity.removeOnPictureInPictureModeChangedListener(this)
+ }
}
- }
withActivity {
addOnPictureInPictureModeChangedListener(listener)
// Add a second listener to force a ConcurrentModificationException
// if not properly handled by ComponentActivity
- addOnPictureInPictureModeChangedListener { }
+ addOnPictureInPictureModeChangedListener {}
onPictureInPictureModeChanged(true)
onPictureInPictureModeChanged(false)
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityLifecycleTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityLifecycleTest.kt
index 2a23d40..d614ddc 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityLifecycleTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityLifecycleTest.kt
@@ -39,8 +39,7 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivityLifecycleTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
@Throws(Throwable::class)
@@ -68,7 +67,8 @@
LifecycleSource.ACTIVITY_CALLBACK to Lifecycle.Event.ON_STOP,
LifecycleSource.ACTIVITY to Lifecycle.Event.ON_DESTROY,
LifecycleSource.ACTIVITY_CALLBACK to Lifecycle.Event.ON_DESTROY
- ).inOrder()
+ )
+ .inOrder()
}
}
@@ -80,9 +80,7 @@
events.add(LifecycleSource.CONTEXT_AWARE to Lifecycle.Event.ON_CREATE)
}
lifecycle.addObserver(
- LifecycleEventObserver { _, event ->
- events.add(LifecycleSource.ACTIVITY to event)
- }
+ LifecycleEventObserver { _, event -> events.add(LifecycleSource.ACTIVITY to event) }
)
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityMenuTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityMenuTest.kt
index f72721a..0644cae 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityMenuTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityMenuTest.kt
@@ -55,33 +55,35 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivityMenuTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun inflatesMenu() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
-
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
- menuHost.addMenuProvider(object : MenuProvider {
- override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
- menuInflater.inflate(R.menu.example_menu, menu)
- }
+ menuHost.addMenuProvider(
+ object : MenuProvider {
+ override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
+ menuInflater.inflate(R.menu.example_menu, menu)
+ }
- override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
- return true
+ override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
+ return true
+ }
}
- })
- menuHost.addMenuProvider(object : MenuProvider {
- override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
- menuInflater.inflate(R.menu.example_menu2, menu)
- }
+ )
+ menuHost.addMenuProvider(
+ object : MenuProvider {
+ override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
+ menuInflater.inflate(R.menu.example_menu2, menu)
+ }
- override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
- return true
+ override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
+ return true
+ }
}
- })
+ )
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item1")).check(matches(isDisplayed()))
@@ -93,23 +95,25 @@
@Test
fun onPrepareMenu() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
var menuPrepared: Boolean
- menuHost.addMenuProvider(object : MenuProvider {
- override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
- menuInflater.inflate(R.menu.example_menu, menu)
- }
+ menuHost.addMenuProvider(
+ object : MenuProvider {
+ override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
+ menuInflater.inflate(R.menu.example_menu, menu)
+ }
- override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
- return true
- }
+ override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
+ return true
+ }
- override fun onPrepareMenu(menu: Menu) {
- menuPrepared = true
+ override fun onPrepareMenu(menu: Menu) {
+ menuPrepared = true
+ }
}
- })
+ )
menuPrepared = false
openActionBarOverflowOrOptionsMenu(menuHost)
@@ -120,46 +124,51 @@
@Test
fun menuItemSelected() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
-
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
var itemSelectedId: Int? = null
- menuHost.addMenuProvider(object : MenuProvider {
- override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
- menuInflater.inflate(R.menu.example_menu, menu)
- }
+ menuHost.addMenuProvider(
+ object : MenuProvider {
+ override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
+ menuInflater.inflate(R.menu.example_menu, menu)
+ }
- override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
- return when (menuItem.itemId) {
- R.id.item1, R.id.item2 -> {
- itemSelectedId = menuItem.itemId
- return true
+ override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
+ return when (menuItem.itemId) {
+ R.id.item1,
+ R.id.item2 -> {
+ itemSelectedId = menuItem.itemId
+ return true
+ }
+ else -> false
}
- else -> false
}
}
- })
+ )
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item1")).perform(click())
assertThat(itemSelectedId).isEqualTo(R.id.item1)
- menuHost.addMenuProvider(object : MenuProvider {
- override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
- menuInflater.inflate(R.menu.example_menu2, menu)
- }
+ menuHost.addMenuProvider(
+ object : MenuProvider {
+ override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
+ menuInflater.inflate(R.menu.example_menu2, menu)
+ }
- override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
- return when (menuItem.itemId) {
- R.id.item3, R.id.item4 -> {
- itemSelectedId = menuItem.itemId
- return true
+ override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
+ return when (menuItem.itemId) {
+ R.id.item3,
+ R.id.item4 -> {
+ itemSelectedId = menuItem.itemId
+ return true
+ }
+ else -> false
}
- else -> false
}
}
- })
+ )
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item3")).perform(click())
@@ -169,23 +178,25 @@
@Test
fun onMenuClosed() {
- withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
var menuClosed = false
- menuHost.addMenuProvider(object : MenuProvider {
- override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
- menuInflater.inflate(R.menu.example_menu, menu)
- }
+ menuHost.addMenuProvider(
+ object : MenuProvider {
+ override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
+ menuInflater.inflate(R.menu.example_menu, menu)
+ }
- override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
- return true
- }
+ override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
+ return true
+ }
- override fun onMenuClosed(menu: Menu) {
- menuClosed = true
+ override fun onMenuClosed(menu: Menu) {
+ menuClosed = true
+ }
}
- })
+ )
openActionBarOverflowOrOptionsMenu(menuHost)
withActivity { closeOptionsMenu() }
@@ -195,7 +206,7 @@
@Test
fun onPanelClosed() {
- withUse(ActivityScenario.launch(ContextMenuComponentActivity::class.java)) {
+ withUse(ActivityScenario.launch(ContextMenuComponentActivity::class.java)) {
onView(withText("Context Menu")).perform(longClick())
onView(withText("Item1")).check(matches(isDisplayed()))
onView(withText("Item2")).check(matches(isDisplayed()))
@@ -210,34 +221,38 @@
@Test
fun menuAPIsCalledWithoutCallingSuper() {
- withUse(ActivityScenario.launch(OptionMenuNoSuperActivity::class.java)) {
+ withUse(ActivityScenario.launch(OptionMenuNoSuperActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
var itemSelectedId: Int? = null
var menuPrepared = false
var menuCreated = false
var menuItemSelected = false
- menuHost.addMenuProvider(object : MenuProvider {
- override fun onPrepareMenu(menu: Menu) {
- menuPrepared = true
- super.onPrepareMenu(menu)
- }
- override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
- menuInflater.inflate(R.menu.example_menu, menu)
- menuCreated = true
- }
+ menuHost.addMenuProvider(
+ object : MenuProvider {
+ override fun onPrepareMenu(menu: Menu) {
+ menuPrepared = true
+ super.onPrepareMenu(menu)
+ }
- override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
- menuItemSelected = true
- return when (menuItem.itemId) {
- R.id.item1, R.id.item2 -> {
- itemSelectedId = menuItem.itemId
- return true
+ override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
+ menuInflater.inflate(R.menu.example_menu, menu)
+ menuCreated = true
+ }
+
+ override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
+ menuItemSelected = true
+ return when (menuItem.itemId) {
+ R.id.item1,
+ R.id.item2 -> {
+ itemSelectedId = menuItem.itemId
+ return true
+ }
+ else -> false
}
- else -> false
}
}
- })
+ )
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item1")).perform(click())
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityOverrideLifecycleTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityOverrideLifecycleTest.kt
index a7769dc..c2a9388 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityOverrideLifecycleTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityOverrideLifecycleTest.kt
@@ -35,8 +35,7 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivityOverrideLifecycleTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@UiThreadTest
@Test
@@ -51,9 +50,8 @@
@Test
fun testOverrideLifecycle() {
- withUse(ActivityScenario.launch(LazyOverrideLifecycleComponentActivity::class.java)) {
- assertThat(withActivity { lifecycle.currentState })
- .isEqualTo(Lifecycle.State.RESUMED)
+ withUse(ActivityScenario.launch(LazyOverrideLifecycleComponentActivity::class.java)) {
+ assertThat(withActivity { lifecycle.currentState }).isEqualTo(Lifecycle.State.RESUMED)
}
}
}
@@ -70,7 +68,5 @@
private var overrideLifecycle: LifecycleRegistry? = null
override val lifecycle: Lifecycle
- get() = overrideLifecycle ?: LifecycleRegistry(this).also {
- overrideLifecycle = it
- }
+ get() = overrideLifecycle ?: LifecycleRegistry(this).also { overrideLifecycle = it }
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityReportFullyDrawnTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityReportFullyDrawnTest.kt
index 1b0c974..fdd8c3c 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityReportFullyDrawnTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityReportFullyDrawnTest.kt
@@ -31,12 +31,11 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivityReportFullyDrawnTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun testReportFullyDrawn() {
- withUse(ActivityScenario.launch(ReportFullyDrawnActivity::class.java)) {
+ withUse(ActivityScenario.launch(ReportFullyDrawnActivity::class.java)) {
withActivity {
// This test makes sure that this method does not throw an exception on devices
// running API 19 (without UPDATE_DEVICE_STATS permission) and earlier
@@ -49,16 +48,8 @@
@Test
fun testReportFullyDrawnRecreate() {
val activity = ActivityScenario.launch(ReportFullyDrawnActivity::class.java)
- activity.withActivity {
- setContentView(
- View(this)
- )
- }
- activity.recreate().withActivity {
- setContentView(
- View(this)
- )
- }
+ activity.withActivity { setContentView(View(this)) }
+ activity.recreate().withActivity { setContentView(View(this)) }
}
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityResultTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityResultTest.kt
index de2cb45..6c755bd 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityResultTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityResultTest.kt
@@ -42,8 +42,7 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivityResultTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun launchInOnCreate() {
@@ -74,7 +73,7 @@
launcher.launch(Intent(this, FinishActivity::class.java))
}
- scenario.withActivity { }
+ scenario.withActivity {}
val latch = scenario.withActivity { launchCountDownLatch }
val list = scenario.withActivity { launchedList }
@@ -110,10 +109,11 @@
}
}
- val launchCountDownLatch = scenario.withActivity {
- assertThat(exceptionThrown).isTrue()
- launchCount
- }
+ val launchCountDownLatch =
+ scenario.withActivity {
+ assertThat(exceptionThrown).isTrue()
+ launchCount
+ }
assertThat(launchCountDownLatch.await(1000, TimeUnit.MILLISECONDS)).isFalse()
}
@@ -131,10 +131,11 @@
}
}
- val launchCountDownLatch = scenario.withActivity {
- assertThat(exceptionThrown).isTrue()
- launchCount
- }
+ val launchCountDownLatch =
+ scenario.withActivity {
+ assertThat(exceptionThrown).isTrue()
+ launchCount
+ }
assertThat(launchCountDownLatch.await(1000, TimeUnit.MILLISECONDS)).isFalse()
}
@@ -142,11 +143,13 @@
}
class PassThroughActivity : ComponentActivity() {
- private val launcher = registerForActivityResult(StartActivityForResult()) {
- if (it.resultCode == Activity.RESULT_OK) {
- finish()
+ private val launcher =
+ registerForActivityResult(StartActivityForResult()) {
+ if (it.resultCode == Activity.RESULT_OK) {
+ finish()
+ }
}
- }
+
@Suppress("DEPRECATION")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -157,19 +160,20 @@
class ResultComponentActivity : ComponentActivity() {
var registryLaunchCount = 0
- val registry = object : ActivityResultRegistry() {
+ val registry =
+ object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- registryLaunchCount++
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ registryLaunchCount++
+ }
}
- }
- val launcher = registerForActivityResult(StartActivityForResult(), registry) { }
+ val launcher = registerForActivityResult(StartActivityForResult(), registry) {}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -186,17 +190,18 @@
init {
addOnContextAvailableListener {
- launcher = if (!recreated) {
- registerForActivityResult(StartActivityForResult()) {
- launchedList.add("first")
- launchCountDownLatch.countDown()
+ launcher =
+ if (!recreated) {
+ registerForActivityResult(StartActivityForResult()) {
+ launchedList.add("first")
+ launchCountDownLatch.countDown()
+ }
+ } else {
+ registerForActivityResult(StartActivityForResult()) {
+ launchedList.add("second")
+ launchCountDownLatch.countDown()
+ }
}
- } else {
- registerForActivityResult(StartActivityForResult()) {
- launchedList.add("second")
- launchCountDownLatch.countDown()
- }
- }
}
}
@@ -214,12 +219,11 @@
var launchCount = CountDownLatch(1)
init {
- launcher = registerForActivityResult(StartActivityForResult()) {
- launchCount.countDown()
- }
- launcherNoLifecycle = activityResultRegistry.register("test", StartActivityForResult()) {
- launchCount.countDown()
- }
+ launcher = registerForActivityResult(StartActivityForResult()) { launchCount.countDown() }
+ launcherNoLifecycle =
+ activityResultRegistry.register("test", StartActivityForResult()) {
+ launchCount.countDown()
+ }
}
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityRunOnNextRecreateTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityRunOnNextRecreateTest.kt
index 4d81f44..84979f0 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityRunOnNextRecreateTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityRunOnNextRecreateTest.kt
@@ -35,8 +35,7 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivityRunOnNextRecreateTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
private class Restarted2 : SavedStateRegistry.AutoRecreated {
override fun onRecreated(owner: SavedStateRegistryOwner) {
@@ -46,10 +45,8 @@
@Test
fun test() {
- withUse(ActivityScenario.launch(AutoRestarterActivity::class.java)) {
- withActivity {
- savedStateRegistry.runOnNextRecreation(Restarted2::class.java)
- }
+ withUse(ActivityScenario.launch(AutoRestarterActivity::class.java)) {
+ withActivity { savedStateRegistry.runOnNextRecreation(Restarted2::class.java) }
recreate()
assertThat(withActivity { observerExecuted }).isTrue()
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivitySavedStateTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivitySavedStateTest.kt
index 95884a8..83e6740 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivitySavedStateTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivitySavedStateTest.kt
@@ -37,8 +37,7 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivitySavedStateTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@After
fun clear() {
@@ -57,7 +56,7 @@
@Test
@Throws(Throwable::class)
fun savedState() {
- withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
+ withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
assertThat(initializeSavedState()).isTrue()
recreate()
moveToState(Lifecycle.State.CREATED)
@@ -72,7 +71,7 @@
@Test
@Throws(Throwable::class)
fun savedStateLateInit() {
- withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
+ withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
assertThat(initializeSavedState()).isTrue()
recreate()
val registry = withActivity { savedStateRegistry }
@@ -83,7 +82,7 @@
@Test
@Throws(Throwable::class)
fun savedStateEarlyRegisterOnCreate() {
- withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
+ withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
assertThat(initializeSavedState()).isTrue()
SavedStateActivity.checkEnabledInOnCreate = true
recreate()
@@ -93,7 +92,7 @@
@Test
@Throws(Throwable::class)
fun savedStateEarlyRegisterOnContextAvailable() {
- withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
+ withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
assertThat(initializeSavedState()).isTrue()
SavedStateActivity.checkEnabledInOnContextAvailable = true
recreate()
@@ -103,7 +102,7 @@
@Test
@Throws(Throwable::class)
fun savedStateEarlyRegisterInitAddedLifecycleObserver() {
- withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
+ withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
assertThat(initializeSavedState()).isTrue()
SavedStateActivity.checkEnabledInInitAddedLifecycleObserver = true
recreate()
@@ -132,16 +131,20 @@
checkEnabledInOnContextAvailable = false
}
}
- lifecycle.addObserver(object : LifecycleEventObserver {
- override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
- if (event == Lifecycle.Event.ON_CREATE &&
- checkEnabledInInitAddedLifecycleObserver &&
- hasDefaultSavedState(savedStateRegistry)) {
- checkEnabledInInitAddedLifecycleObserver = false
- lifecycle.removeObserver(this)
+ lifecycle.addObserver(
+ object : LifecycleEventObserver {
+ override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
+ if (
+ event == Lifecycle.Event.ON_CREATE &&
+ checkEnabledInInitAddedLifecycleObserver &&
+ hasDefaultSavedState(savedStateRegistry)
+ ) {
+ checkEnabledInInitAddedLifecycleObserver = false
+ lifecycle.removeObserver(this)
+ }
}
}
- })
+ )
}
override fun onCreate(savedInstanceState: Bundle?) {
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityViewModelTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityViewModelTest.kt
index f770904..aa45f7c 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityViewModelTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentActivityViewModelTest.kt
@@ -40,8 +40,7 @@
@RunWith(AndroidJUnit4::class)
class ComponentActivityViewModelTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test(expected = IllegalStateException::class)
@UiThreadTest
@@ -52,36 +51,32 @@
@Test
fun testSameViewModelStorePrePostOnCreate() {
- withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
+ withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
val originalStore = withActivity { preOnCreateViewModelStore }
assertWithMessage(
- "Pre-onCreate() ViewModelStore should equal the post-onCreate() ViewModelStore"
- )
+ "Pre-onCreate() ViewModelStore should equal the post-onCreate() ViewModelStore"
+ )
.that(originalStore)
.isSameInstanceAs(withActivity { postOnCreateViewModelStore })
recreate()
- assertThat(withActivity { preOnCreateViewModelStore })
- .isSameInstanceAs(originalStore)
- assertThat(withActivity { postOnCreateViewModelStore })
- .isSameInstanceAs(originalStore)
+ assertThat(withActivity { preOnCreateViewModelStore }).isSameInstanceAs(originalStore)
+ assertThat(withActivity { postOnCreateViewModelStore }).isSameInstanceAs(originalStore)
}
}
@Test
fun testSameActivityViewModels() {
- withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
+ withUse(ActivityScenario.launch(ViewModelActivity::class.java)) {
val activityModel = withActivity { activityModel }
val defaultActivityModel = withActivity { defaultActivityModel }
assertThat(defaultActivityModel).isNotSameInstanceAs(activityModel)
recreate()
- assertThat(withActivity { activityModel })
- .isSameInstanceAs(activityModel)
- assertThat(withActivity { defaultActivityModel })
- .isSameInstanceAs(defaultActivityModel)
+ assertThat(withActivity { activityModel }).isSameInstanceAs(activityModel)
+ assertThat(withActivity { defaultActivityModel }).isSameInstanceAs(defaultActivityModel)
}
}
@@ -122,12 +117,12 @@
ViewModelProvider(
viewModelStore,
defaultViewModelProviderFactory,
- defaultViewModelCreationExtras)["test", TestViewModel::class.java]
+ defaultViewModelCreationExtras
+ )["test", TestViewModel::class.java]
}
recreate()
- assertThat(withActivity {
- ViewModelProvider(this)["test", TestViewModel::class.java]
- }).isSameInstanceAs(creationViewModel)
+ assertThat(withActivity { ViewModelProvider(this)["test", TestViewModel::class.java] })
+ .isSameInstanceAs(creationViewModel)
}
}
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ComponentDialogTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ComponentDialogTest.kt
index 9517064e..c6b6b84 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ComponentDialogTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ComponentDialogTest.kt
@@ -40,26 +40,19 @@
@RunWith(AndroidJUnit4::class)
class ComponentDialogTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun testLifecycle() {
- withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
- val dialog = withActivity {
- ComponentDialog(this)
- }
+ withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
+ val dialog = withActivity { ComponentDialog(this) }
val lifecycle = dialog.lifecycle
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.INITIALIZED)
- onActivity {
- dialog.show()
- }
+ onActivity { dialog.show() }
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
- onActivity {
- dialog.dismiss()
- }
+ onActivity { dialog.dismiss() }
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED)
assertWithMessage("A new Lifecycle object should be created after destruction")
@@ -73,11 +66,7 @@
@Throws(Throwable::class)
fun savedState() {
withUse(ActivityScenario.launch(SavedStateActivity::class.java)) {
- val dialog = withActivity {
- ComponentDialog(this).also {
- it.show()
- }
- }
+ val dialog = withActivity { ComponentDialog(this).also { it.show() } }
val lifecycle = dialog.lifecycle
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
@@ -92,13 +81,9 @@
// Destroy dialog and restore saved instance state
val savedState = dialog.onSaveInstanceState()
assertThat(savedState).isNotNull()
- onActivity {
- dialog.dismiss()
- }
+ onActivity { dialog.dismiss() }
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED)
- val restoredDialog = withActivity {
- ComponentDialog(this)
- }
+ val restoredDialog = withActivity { ComponentDialog(this) }
withActivity {
assertThat((restoredDialog.lifecycle as LifecycleRegistry).currentState)
.isEqualTo(Lifecycle.State.INITIALIZED)
@@ -111,11 +96,7 @@
@Test
fun testViewTreeSavedStateRegistryOwner() {
withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
- val dialog = withActivity {
- ViewOwnerDialog(this).also {
- it.show()
- }
- }
+ val dialog = withActivity { ViewOwnerDialog(this).also { it.show() } }
val lifecycle = dialog.lifecycle
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
@@ -133,13 +114,9 @@
// Destroy dialog and restore saved instance state
val savedState = dialog.onSaveInstanceState()
assertThat(savedState).isNotNull()
- onActivity {
- dialog.dismiss()
- }
+ onActivity { dialog.dismiss() }
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED)
- val restoredDialog = withActivity {
- ViewOwnerDialog(this)
- }
+ val restoredDialog = withActivity { ViewOwnerDialog(this) }
withActivity {
assertThat((restoredDialog.lifecycle as LifecycleRegistry).currentState)
.isEqualTo(Lifecycle.State.INITIALIZED)
@@ -154,48 +131,32 @@
@Test
fun testOnBackPressed() {
- withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
- val dialog = withActivity {
- DoubleTapBackDialog(this).also {
- it.show()
- }
- }
+ withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
+ val dialog = withActivity { DoubleTapBackDialog(this).also { it.show() } }
val lifecycle = dialog.lifecycle
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
- onActivity {
- dialog.onBackPressed()
- }
+ onActivity { dialog.onBackPressed() }
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
assertThat(dialog.backCount).isEqualTo(1)
- onActivity {
- dialog.onBackPressed()
- }
+ onActivity { dialog.onBackPressed() }
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED)
}
}
@Test
fun testViewTreeOnBackPressedDispatcherOwner() {
- withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
- val dialog = withActivity {
- ViewOwnerDialog(this).also {
- it.show()
- }
- }
+ withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
+ val dialog = withActivity { ViewOwnerDialog(this).also { it.show() } }
val lifecycle = dialog.lifecycle
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
- onActivity {
- dialog.onBackPressed()
- }
+ onActivity { dialog.onBackPressed() }
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED)
assertThat(dialog.view.backCount).isEqualTo(1)
- onActivity {
- dialog.onBackPressed()
- }
+ onActivity { dialog.onBackPressed() }
assertThat(lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED)
}
}
@@ -204,12 +165,13 @@
class DoubleTapBackDialog(context: Context) : ComponentDialog(context) {
var backCount = 0
- private val onBackPressedCallback = object : OnBackPressedCallback(true) {
- override fun handleOnBackPressed() {
- backCount++
- remove()
+ private val onBackPressedCallback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {
+ backCount++
+ remove()
+ }
}
- }
init {
onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
@@ -226,12 +188,13 @@
class BackHandlingView(context: Context) : View(context) {
var backCount = 0
- private val onBackPressedCallback = object : OnBackPressedCallback(true) {
- override fun handleOnBackPressed() {
- backCount++
- remove()
+ private val onBackPressedCallback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {
+ backCount++
+ remove()
+ }
}
- }
override fun onAttachedToWindow() {
super.onAttachedToWindow()
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ContentViewTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ContentViewTest.kt
index fe85d84..2ac8905 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ContentViewTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ContentViewTest.kt
@@ -40,21 +40,19 @@
@RunWith(AndroidJUnit4::class)
class ContentViewTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun testLifecycleObserver() {
- withUse(ActivityScenario.launch(ContentViewActivity::class.java)) {
+ withUse(ActivityScenario.launch(ContentViewActivity::class.java)) {
val inflatedTextView: TextView = withActivity { findViewById(R.id.inflated_text_view) }
- assertThat(inflatedTextView)
- .isNotNull()
+ assertThat(inflatedTextView).isNotNull()
}
}
@Test
fun testViewTreeInflation() {
- withUse(ActivityScenario.launch(ContentViewActivity::class.java)) {
+ withUse(ActivityScenario.launch(ContentViewActivity::class.java)) {
val inflatedTextView: TextView = withActivity { findViewById(R.id.inflated_text_view) }
withActivity {
@@ -82,39 +80,43 @@
}
}
- private fun runAttachTest(
- message: String,
- attach: ComponentActivity.(View) -> Unit
- ) {
- withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
+ private fun runAttachTest(message: String, attach: ComponentActivity.(View) -> Unit) {
+ withUse(ActivityScenario.launch(EmptyContentActivity::class.java)) {
withActivity {
val view = View(this)
var attachedLifecycleOwner: Any? = "did not attach"
var attachedViewModelStoreOwner: Any? = "did not attach"
var attachedSavedStateRegistryOwner: Any? = "did not attach"
- view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
- override fun onViewDetachedFromWindow(v: View) {
- // Do nothing
- }
+ view.addOnAttachStateChangeListener(
+ object : View.OnAttachStateChangeListener {
+ override fun onViewDetachedFromWindow(v: View) {
+ // Do nothing
+ }
- override fun onViewAttachedToWindow(v: View) {
- attachedLifecycleOwner = view.findViewTreeLifecycleOwner()
- attachedViewModelStoreOwner = view.findViewTreeViewModelStoreOwner()
- attachedSavedStateRegistryOwner = view.findViewTreeSavedStateRegistryOwner()
+ override fun onViewAttachedToWindow(v: View) {
+ attachedLifecycleOwner = view.findViewTreeLifecycleOwner()
+ attachedViewModelStoreOwner = view.findViewTreeViewModelStoreOwner()
+ attachedSavedStateRegistryOwner =
+ view.findViewTreeSavedStateRegistryOwner()
+ }
}
- })
+ )
attach(view)
assertWithMessage("$message: ViewTreeLifecycleOwner was set correctly")
- .that(attachedLifecycleOwner).isSameInstanceAs(this)
+ .that(attachedLifecycleOwner)
+ .isSameInstanceAs(this)
assertWithMessage("$message: ViewTreeViewModelStoreOwner was set correctly")
- .that(attachedViewModelStoreOwner).isSameInstanceAs(this)
+ .that(attachedViewModelStoreOwner)
+ .isSameInstanceAs(this)
assertWithMessage("$message: ViewTreeSavedStateRegistryOwner was set correctly")
- .that(attachedSavedStateRegistryOwner).isSameInstanceAs(this)
+ .that(attachedSavedStateRegistryOwner)
+ .isSameInstanceAs(this)
}
}
}
}
class ContentViewActivity : ComponentActivity(R.layout.activity_inflates_res)
+
class EmptyContentActivity : ComponentActivity()
diff --git a/activity/activity/src/androidTest/java/androidx/activity/EdgeToEdgeTest.kt b/activity/activity/src/androidTest/java/androidx/activity/EdgeToEdgeTest.kt
index 3dccbc9..004ca84 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/EdgeToEdgeTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/EdgeToEdgeTest.kt
@@ -61,13 +61,13 @@
}
}
if (Build.VERSION.SDK_INT >= 30) {
- assertThat(window.attributes.layoutInDisplayCutoutMode).isEqualTo(
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
- )
+ assertThat(window.attributes.layoutInDisplayCutoutMode)
+ .isEqualTo(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS)
} else if (Build.VERSION.SDK_INT >= 28) {
- assertThat(window.attributes.layoutInDisplayCutoutMode).isEqualTo(
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
- )
+ assertThat(window.attributes.layoutInDisplayCutoutMode)
+ .isEqualTo(
+ WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ )
}
}
}
@@ -79,8 +79,8 @@
withActivity {
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.auto(Color.CYAN, Color.DKGRAY) { _ -> false },
- navigationBarStyle = SystemBarStyle
- .auto(Color.CYAN, Color.DKGRAY) { _ -> false }
+ navigationBarStyle =
+ SystemBarStyle.auto(Color.CYAN, Color.DKGRAY) { _ -> false }
)
val view = window.decorView
if (Build.VERSION.SDK_INT >= 29) {
@@ -105,13 +105,13 @@
}
}
if (Build.VERSION.SDK_INT >= 30) {
- assertThat(window.attributes.layoutInDisplayCutoutMode).isEqualTo(
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
- )
+ assertThat(window.attributes.layoutInDisplayCutoutMode)
+ .isEqualTo(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS)
} else if (Build.VERSION.SDK_INT >= 28) {
- assertThat(window.attributes.layoutInDisplayCutoutMode).isEqualTo(
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
- )
+ assertThat(window.attributes.layoutInDisplayCutoutMode)
+ .isEqualTo(
+ WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ )
}
}
}
@@ -141,13 +141,13 @@
}
}
if (Build.VERSION.SDK_INT >= 30) {
- assertThat(window.attributes.layoutInDisplayCutoutMode).isEqualTo(
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
- )
+ assertThat(window.attributes.layoutInDisplayCutoutMode)
+ .isEqualTo(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS)
} else if (Build.VERSION.SDK_INT >= 28) {
- assertThat(window.attributes.layoutInDisplayCutoutMode).isEqualTo(
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
- )
+ assertThat(window.attributes.layoutInDisplayCutoutMode)
+ .isEqualTo(
+ WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ )
}
}
}
@@ -177,13 +177,13 @@
}
}
if (Build.VERSION.SDK_INT >= 30) {
- assertThat(window.attributes.layoutInDisplayCutoutMode).isEqualTo(
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
- )
+ assertThat(window.attributes.layoutInDisplayCutoutMode)
+ .isEqualTo(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS)
} else if (Build.VERSION.SDK_INT >= 28) {
- assertThat(window.attributes.layoutInDisplayCutoutMode).isEqualTo(
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
- )
+ assertThat(window.attributes.layoutInDisplayCutoutMode)
+ .isEqualTo(
+ WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ )
}
}
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/FullyDrawnReporterTest.kt b/activity/activity/src/androidTest/java/androidx/activity/FullyDrawnReporterTest.kt
index 0edb154..460c280 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/FullyDrawnReporterTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/FullyDrawnReporterTest.kt
@@ -39,20 +39,21 @@
@RunWith(AndroidJUnit4::class)
class FullyDrawnReporterTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun findFullyDrawnReporterOwner() {
withUse(ActivityScenario.launch(FullyDrawnActivity::class.java)) {
- val provider1 = object : FullyDrawnReporterOwner {
- override val fullyDrawnReporter: FullyDrawnReporter
- get() = withActivity { fullyDrawnReporter }
- }
- val provider2 = object : FullyDrawnReporterOwner {
- override val fullyDrawnReporter: FullyDrawnReporter
- get() = withActivity { fullyDrawnReporter }
- }
+ val provider1 =
+ object : FullyDrawnReporterOwner {
+ override val fullyDrawnReporter: FullyDrawnReporter
+ get() = withActivity { fullyDrawnReporter }
+ }
+ val provider2 =
+ object : FullyDrawnReporterOwner {
+ override val fullyDrawnReporter: FullyDrawnReporter
+ get() = withActivity { fullyDrawnReporter }
+ }
val view = withActivity {
val view = View(this)
setContentView(view)
@@ -61,8 +62,7 @@
view
}
withActivity {
- assertThat(view.findViewTreeFullyDrawnReporterOwner())
- .isSameInstanceAs(provider2)
+ assertThat(view.findViewTreeFullyDrawnReporterOwner()).isSameInstanceAs(provider2)
assertThat(window.decorView.findViewTreeFullyDrawnReporterOwner())
.isSameInstanceAs(provider1)
assertThat((view.parent as View).findViewTreeFullyDrawnReporterOwner())
@@ -89,14 +89,10 @@
}
}
delay(1L)
- waitForOnDrawComplete {
- assertThat(fullyDrawnReported).isFalse()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReported).isFalse() }
mutex.unlock()
delay(1L)
- waitForOnDrawComplete {
- assertThat(fullyDrawnReported).isTrue()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReported).isTrue() }
}
}
}
@@ -109,13 +105,9 @@
fullyDrawnReporter.addReporter()
fullyDrawnReporter.removeReporter()
- waitForOnDrawComplete {
- assertThat(fullyDrawnReported).isFalse()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReported).isFalse() }
fullyDrawnReporter.removeReporter()
- waitForOnDrawComplete {
- assertThat(fullyDrawnReported).isTrue()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReported).isTrue() }
}
}
@@ -135,14 +127,10 @@
delay(1L) // wait for launch
fullyDrawnReporter.removeReporter()
- waitForOnDrawComplete {
- assertThat(fullyDrawnReported).isFalse()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReported).isFalse() }
mutex.unlock()
delay(1L) // allow launch to continue
- waitForOnDrawComplete {
- assertThat(fullyDrawnReported).isTrue()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReported).isTrue() }
}
}
}
@@ -163,14 +151,10 @@
delay(1L) // wait for launch
mutex.unlock()
delay(1L) // allow launch to continue
- waitForOnDrawComplete {
- assertThat(fullyDrawnReported).isFalse()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReported).isFalse() }
fullyDrawnReporter.removeReporter()
- waitForOnDrawComplete {
- assertThat(fullyDrawnReported).isTrue()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReported).isTrue() }
}
}
}
@@ -185,9 +169,7 @@
val reportListener2 = { report2 = true }
val reportListener3 = { report3 = true }
- withActivity {
- setContentView(View(this))
- }
+ withActivity { setContentView(View(this)) }
val fullyDrawnReporter = withActivity { fullyDrawnReporter }
fullyDrawnReporter.addReporter()
fullyDrawnReporter.addOnReportDrawnListener(reportListener1)
@@ -210,9 +192,7 @@
@Test
fun fakeoutReport() {
withUse(ActivityScenario.launch(FullyDrawnActivity::class.java)) {
- withActivity {
- setContentView(View(this))
- }
+ withActivity { setContentView(View(this)) }
val fullyDrawnReporter = withActivity { fullyDrawnReporter }
onActivity {
@@ -220,27 +200,17 @@
fullyDrawnReporter.removeReporter()
fullyDrawnReporter.addReporter()
}
- waitForOnDrawComplete {
- assertThat(fullyDrawnReporter.isFullyDrawnReported).isFalse()
- }
- onActivity {
- fullyDrawnReporter.removeReporter()
- }
- waitForOnDrawComplete {
- assertThat(fullyDrawnReporter.isFullyDrawnReported).isTrue()
- }
+ waitForOnDrawComplete { assertThat(fullyDrawnReporter.isFullyDrawnReported).isFalse() }
+ onActivity { fullyDrawnReporter.removeReporter() }
+ waitForOnDrawComplete { assertThat(fullyDrawnReporter.isFullyDrawnReported).isTrue() }
}
}
- /**
- * The [ComponentActivity.reportFullyDrawn] should be called during OnDraw.
- */
+ /** The [ComponentActivity.reportFullyDrawn] should be called during OnDraw. */
@Test
fun reportedInOnDraw() {
withUse(ActivityScenario.launch(FullyDrawnActivity::class.java)) {
- withActivity {
- setContentView(View(this))
- }
+ withActivity { setContentView(View(this)) }
val fullyDrawnReporter = withActivity { fullyDrawnReporter }
var fullyDrawnInOnDraw = false
@@ -251,14 +221,17 @@
OneShotPreDrawListener.add(activity.window.decorView) {
fullyDrawnInOnPreDraw = fullyDrawnReporter.isFullyDrawnReported
}
- val onDrawListener = object : OnDrawListener {
- override fun onDraw() {
- fullyDrawnInOnDraw = fullyDrawnReporter.isFullyDrawnReported
- activity.window.decorView.post {
- activity.window.decorView.viewTreeObserver.removeOnDrawListener(this)
+ val onDrawListener =
+ object : OnDrawListener {
+ override fun onDraw() {
+ fullyDrawnInOnDraw = fullyDrawnReporter.isFullyDrawnReported
+ activity.window.decorView.post {
+ activity.window.decorView.viewTreeObserver.removeOnDrawListener(
+ this
+ )
+ }
}
}
- }
activity.window.decorView.viewTreeObserver.addOnDrawListener(onDrawListener)
}
waitForOnDrawComplete {
@@ -272,9 +245,7 @@
block: FullyDrawnActivity.() -> Unit = {}
) {
val countDownLatch = CountDownLatch(1)
- val observer = OnDrawListener {
- countDownLatch.countDown()
- }
+ val observer = OnDrawListener { countDownLatch.countDown() }
withActivity {
runOnUiThread {
window.decorView.viewTreeObserver.addOnDrawListener(observer)
@@ -283,9 +254,7 @@
}
assertThat(countDownLatch.await(10, TimeUnit.SECONDS)).isTrue()
withActivity {
- runOnUiThread {
- window.decorView.viewTreeObserver.removeOnDrawListener(observer)
- }
+ runOnUiThread { window.decorView.viewTreeObserver.removeOnDrawListener(observer) }
block()
}
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/LeakCanaryApp.kt b/activity/activity/src/androidTest/java/androidx/activity/LeakCanaryApp.kt
index 25b7fc9..c73d9f93 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/LeakCanaryApp.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/LeakCanaryApp.kt
@@ -25,11 +25,12 @@
override fun onCreate() {
super.onCreate()
@Suppress("UNCHECKED_CAST")
- LeakCanary.config = LeakCanary.config.copy(
- referenceMatchers = (
- AndroidReferenceMatchers.appDefaults - AndroidReferenceMatchers
- .INPUT_METHOD_MANAGER_IS_TERRIBLE
- ) as List<ReferenceMatcher>
- )
+ LeakCanary.config =
+ LeakCanary.config.copy(
+ referenceMatchers =
+ (AndroidReferenceMatchers.appDefaults -
+ AndroidReferenceMatchers.INPUT_METHOD_MANAGER_IS_TERRIBLE)
+ as List<ReferenceMatcher>
+ )
}
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/LeakInputMethodManagerTest.kt b/activity/activity/src/androidTest/java/androidx/activity/LeakInputMethodManagerTest.kt
index ee4318b..d9c2f54 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/LeakInputMethodManagerTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/LeakInputMethodManagerTest.kt
@@ -42,14 +42,12 @@
// Detect leaks BEFORE and AFTER activity is destroyed
@get:Rule
- val ruleChain: RuleChain = RuleChain.outerRule(DetectLeaksAfterTestSuccess())
- .around(activityRule)
+ val ruleChain: RuleChain =
+ RuleChain.outerRule(DetectLeaksAfterTestSuccess()).around(activityRule)
@Test
fun leakThroughRemovedEditText() {
- activityRule.runOnUiThread {
- activityRule.activity.removeEditText()
- }
+ activityRule.runOnUiThread { activityRule.activity.removeEditText() }
activityRule.activity.blockingFinish()
}
}
@@ -58,6 +56,7 @@
private val timeout = 10L // sec
private val latch = CountDownLatch(1)
private lateinit var editText: EditText
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val layout = LinearLayout(this)
diff --git a/activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherInvokerTest.kt b/activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherInvokerTest.kt
index 7c6ae0f..0cca2f3 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherInvokerTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherInvokerTest.kt
@@ -38,30 +38,31 @@
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.S_V2)
class OnBackPressedDispatcherInvokerTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun testSimpleInvoker() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackPressed() { }
- }
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {}
+ }
dispatcher.addCallback(callback)
@@ -76,23 +77,25 @@
fun testInvokerEnableDisable() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackPressed() { }
- }
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {}
+ }
dispatcher.addCallback(callback)
@@ -109,11 +112,12 @@
@Test
fun testCallbackEnabledDisabled() {
- val callback = object : OnBackPressedCallback(false) {
- override fun handleOnBackPressed() {
- TODO("Not yet implemented")
+ val callback =
+ object : OnBackPressedCallback(false) {
+ override fun handleOnBackPressed() {
+ TODO("Not yet implemented")
+ }
}
- }
callback.isEnabled = true
callback.isEnabled = false
@@ -123,19 +127,21 @@
fun testInvokerAddDisabledCallback() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
+
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ val callback =
+ object : OnBackPressedCallback(false) {
+ override fun handleOnBackPressed() {}
}
- }
-
- val callback = object : OnBackPressedCallback(false) {
- override fun handleOnBackPressed() { }
- }
val dispatcher = OnBackPressedDispatcher()
@@ -158,19 +164,21 @@
fun testInvokerAddEnabledCallbackBeforeSet() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
+
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {}
}
- }
-
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackPressed() { }
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(callback)
@@ -188,15 +196,16 @@
fun testSimpleAnimatedCallback() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
@@ -205,19 +214,22 @@
var startedCount = 0
var progressedCount = 0
var cancelledCount = 0
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackStarted(backEvent: BackEventCompat) {
- startedCount++
- }
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {
+ startedCount++
+ }
- override fun handleOnBackProgressed(backEvent: BackEventCompat) {
- progressedCount++
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {
+ progressedCount++
+ }
+
+ override fun handleOnBackPressed() {}
+
+ override fun handleOnBackCancelled() {
+ cancelledCount++
+ }
}
- override fun handleOnBackPressed() { }
- override fun handleOnBackCancelled() {
- cancelledCount++
- }
- }
dispatcher.addCallback(callback)
@@ -241,29 +253,34 @@
fun testSimpleAnimatedCallbackRemovedCancel() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
var cancelledCount = 0
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackStarted(backEvent: BackEventCompat) { }
- override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
- override fun handleOnBackPressed() { }
- override fun handleOnBackCancelled() {
- cancelledCount++
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackPressed() {}
+
+ override fun handleOnBackCancelled() {
+ cancelledCount++
+ }
}
- }
dispatcher.addCallback(callback)
@@ -281,31 +298,36 @@
fun testSimpleAnimatedCallbackRemovedCancelInHandleOnStarted() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
var cancelledCount = 0
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackStarted(backEvent: BackEventCompat) {
- this.remove()
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {
+ this.remove()
+ }
+
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackPressed() {}
+
+ override fun handleOnBackCancelled() {
+ cancelledCount++
+ }
}
- override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
- override fun handleOnBackPressed() { }
- override fun handleOnBackCancelled() {
- cancelledCount++
- }
- }
dispatcher.addCallback(callback)
@@ -322,29 +344,34 @@
fun testSimpleAnimatedCallbackAddedContinue() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
var completedCount = 0
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackStarted(backEvent: BackEventCompat) { }
- override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
- override fun handleOnBackPressed() {
- completedCount++
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackPressed() {
+ completedCount++
+ }
+
+ override fun handleOnBackCancelled() {}
}
- override fun handleOnBackCancelled() { }
- }
dispatcher.addCallback(callback)
@@ -352,9 +379,11 @@
dispatcher.dispatchOnBackStarted(BackEventCompat(0.1F, 0.1F, 0.1F, EDGE_LEFT))
- dispatcher.addCallback(object : OnBackPressedCallback(true) {
- override fun handleOnBackPressed() { }
- })
+ dispatcher.addCallback(
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {}
+ }
+ )
dispatcher.onBackPressed()
@@ -365,29 +394,34 @@
fun testLifecycleAnimatedCallbackAddedContinue() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
var completedCount = 0
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackStarted(backEvent: BackEventCompat) { }
- override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
- override fun handleOnBackPressed() {
- completedCount++
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackPressed() {
+ completedCount++
+ }
+
+ override fun handleOnBackCancelled() {}
}
- override fun handleOnBackCancelled() { }
- }
val lifecycleOwner = TestLifecycleOwner(Lifecycle.State.RESUMED)
@@ -398,9 +432,11 @@
dispatcher.dispatchOnBackStarted(BackEventCompat(0.1F, 0.1F, 0.1F, EDGE_LEFT))
lifecycleOwner.currentState = Lifecycle.State.STARTED
- dispatcher.addCallback(object : OnBackPressedCallback(true) {
- override fun handleOnBackPressed() { }
- })
+ dispatcher.addCallback(
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {}
+ }
+ )
dispatcher.onBackPressed()
@@ -411,29 +447,34 @@
fun testSimpleAnimatedLifecycleCallbackRemovedCancel() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
var cancelledCount = 0
- val callback = object : OnBackPressedCallback(true) {
- override fun handleOnBackStarted(backEvent: BackEventCompat) { }
- override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
- override fun handleOnBackPressed() { }
- override fun handleOnBackCancelled() {
- cancelledCount++
+ val callback =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackPressed() {}
+
+ override fun handleOnBackCancelled() {
+ cancelledCount++
+ }
}
- }
val lifecycleOwner = TestLifecycleOwner(Lifecycle.State.RESUMED)
@@ -455,29 +496,34 @@
fun testDoubleStartCallbackCausesCancel() {
var registerCount = 0
var unregisterCount = 0
- val invoker = object : OnBackInvokedDispatcher {
- override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
- registerCount++
- }
+ val invoker =
+ object : OnBackInvokedDispatcher {
+ override fun registerOnBackInvokedCallback(p0: Int, p1: OnBackInvokedCallback) {
+ registerCount++
+ }
- override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
- unregisterCount++
+ override fun unregisterOnBackInvokedCallback(p0: OnBackInvokedCallback) {
+ unregisterCount++
+ }
}
- }
val dispatcher = OnBackPressedDispatcher()
dispatcher.setOnBackInvokedDispatcher(invoker)
var cancelledCount = 0
- val callback1 = object : OnBackPressedCallback(true) {
- override fun handleOnBackStarted(backEvent: BackEventCompat) { }
- override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
- override fun handleOnBackPressed() { }
- override fun handleOnBackCancelled() {
- cancelledCount++
+ val callback1 =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackPressed() {}
+
+ override fun handleOnBackCancelled() {
+ cancelledCount++
+ }
}
- }
dispatcher.addCallback(callback1)
@@ -487,14 +533,18 @@
var startedCount2 = 0
- val callback2 = object : OnBackPressedCallback(true) {
- override fun handleOnBackStarted(backEvent: BackEventCompat) {
- startedCount2++
+ val callback2 =
+ object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {
+ startedCount2++
+ }
+
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
+
+ override fun handleOnBackPressed() {}
+
+ override fun handleOnBackCancelled() {}
}
- override fun handleOnBackProgressed(backEvent: BackEventCompat) {}
- override fun handleOnBackPressed() { }
- override fun handleOnBackCancelled() { }
- }
dispatcher.addCallback(callback2)
diff --git a/activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherTest.kt b/activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherTest.kt
index 71d9294b..eb6a9b0 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/OnBackPressedDispatcherTest.kt
@@ -41,15 +41,12 @@
private var fallbackCount = 0
lateinit var dispatcher: OnBackPressedDispatcher
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Before
fun setup() {
fallbackCount = 0
- dispatcher = OnBackPressedDispatcher {
- fallbackCount++
- }
+ dispatcher = OnBackPressedDispatcher { fallbackCount++ }
}
@UiThreadTest
@@ -86,13 +83,12 @@
@Test
fun testIsEnabledWithinCallback() {
var count = 0
- val callback = dispatcher.addCallback {
- count++
- isEnabled = false
- }
- assertWithMessage("Callback should be enabled by default")
- .that(callback.isEnabled)
- .isTrue()
+ val callback =
+ dispatcher.addCallback {
+ count++
+ isEnabled = false
+ }
+ assertWithMessage("Callback should be enabled by default").that(callback.isEnabled).isTrue()
assertWithMessage("Dispatcher should have an enabled callback")
.that(dispatcher.hasEnabledCallbacks())
.isTrue()
@@ -129,9 +125,8 @@
onBackPressedCallback.remove()
assertWithMessage(
- "Handler should return false when no OnBackPressedCallbacks " +
- "are registered"
- )
+ "Handler should return false when no OnBackPressedCallbacks " + "are registered"
+ )
.that(dispatcher.hasEnabledCallbacks())
.isFalse()
dispatcher.onBackPressed()
@@ -139,20 +134,19 @@
assertWithMessage("Count shouldn't be incremented after removal")
.that(onBackPressedCallback.count)
.isEqualTo(1)
- assertWithMessage("Fallback count should be incremented")
- .that(fallbackCount)
- .isEqualTo(1)
+ assertWithMessage("Fallback count should be incremented").that(fallbackCount).isEqualTo(1)
}
@UiThreadTest
@Test
fun testRemoveInCallback() {
- val onBackPressedCallback = object : CountingOnBackPressedCallback() {
- override fun handleOnBackPressed() {
- super.handleOnBackPressed()
- remove()
+ val onBackPressedCallback =
+ object : CountingOnBackPressedCallback() {
+ override fun handleOnBackPressed() {
+ super.handleOnBackPressed()
+ remove()
+ }
}
- }
dispatcher.addCallback(onBackPressedCallback)
assertWithMessage("Handler should return true once a callback is added")
@@ -164,9 +158,8 @@
.isEqualTo(1)
assertWithMessage(
- "Handler should return false when no OnBackPressedCallbacks " +
- "are registered"
- )
+ "Handler should return false when no OnBackPressedCallbacks " + "are registered"
+ )
.that(dispatcher.hasEnabledCallbacks())
.isFalse()
dispatcher.onBackPressed()
@@ -244,9 +237,9 @@
.that(disabledOnBackPressedCallback.count)
.isEqualTo(0)
assertWithMessage(
- "Previous callbacks should be incremented if more recent callbacks " +
- "were disabled"
- )
+ "Previous callbacks should be incremented if more recent callbacks " +
+ "were disabled"
+ )
.that(onBackPressedCallback.count)
.isEqualTo(1)
assertWithMessage("Fallback count should not be incremented")
@@ -258,14 +251,15 @@
@Test
fun testPassthroughListener() {
val onBackPressedCallback = CountingOnBackPressedCallback()
- val passThroughOnBackPressedCallback = object : CountingOnBackPressedCallback() {
- override fun handleOnBackPressed() {
- super.handleOnBackPressed()
- // Trigger the next listener
- isEnabled = false
- dispatcher.onBackPressed()
+ val passThroughOnBackPressedCallback =
+ object : CountingOnBackPressedCallback() {
+ override fun handleOnBackPressed() {
+ super.handleOnBackPressed()
+ // Trigger the next listener
+ isEnabled = false
+ dispatcher.onBackPressed()
+ }
}
- }
dispatcher.addCallback(onBackPressedCallback)
dispatcher.addCallback(passThroughOnBackPressedCallback)
@@ -274,9 +268,9 @@
.that(passThroughOnBackPressedCallback.count)
.isEqualTo(1)
assertWithMessage(
- "Previous callbacks should be incremented if more recent callbacks " +
- "disabled itself and called onBackPressed()"
- )
+ "Previous callbacks should be incremented if more recent callbacks " +
+ "disabled itself and called onBackPressed()"
+ )
.that(onBackPressedCallback.count)
.isEqualTo(1)
assertWithMessage("Fallback count should not be incremented")
@@ -298,9 +292,9 @@
.that(lifecycleOnBackPressedCallback.count)
.isEqualTo(0)
assertWithMessage(
- "Previous callbacks should be incremented if more recent callbacks " +
- "aren't started"
- )
+ "Previous callbacks should be incremented if more recent callbacks " +
+ "aren't started"
+ )
.that(onBackPressedCallback.count)
.isEqualTo(1)
@@ -321,9 +315,9 @@
.that(lifecycleOnBackPressedCallback.count)
.isEqualTo(1)
assertWithMessage(
- "Previous callbacks should be incremented if more recent callbacks " +
- "aren't started"
- )
+ "Previous callbacks should be incremented if more recent callbacks " +
+ "aren't started"
+ )
.that(onBackPressedCallback.count)
.isEqualTo(2)
@@ -334,9 +328,9 @@
.that(lifecycleOnBackPressedCallback.count)
.isEqualTo(1)
assertWithMessage(
- "Previous callbacks should be incremented if more recent callbacks " +
- "aren't started"
- )
+ "Previous callbacks should be incremented if more recent callbacks " +
+ "aren't started"
+ )
.that(onBackPressedCallback.count)
.isEqualTo(3)
}
@@ -344,12 +338,13 @@
@UiThreadTest
@Test
fun testLifecycleRemoveInCallback() {
- val onBackPressedCallback = object : CountingOnBackPressedCallback() {
- override fun handleOnBackPressed() {
- super.handleOnBackPressed()
- remove()
+ val onBackPressedCallback =
+ object : CountingOnBackPressedCallback() {
+ override fun handleOnBackPressed() {
+ super.handleOnBackPressed()
+ remove()
+ }
}
- }
val lifecycleOwner = TestLifecycleOwner()
dispatcher.addCallback(lifecycleOwner, onBackPressedCallback)
@@ -362,9 +357,8 @@
.isEqualTo(1)
assertWithMessage(
- "Handler should return false when no OnBackPressedCallbacks " +
- "are registered"
- )
+ "Handler should return false when no OnBackPressedCallbacks " + "are registered"
+ )
.that(dispatcher.hasEnabledCallbacks())
.isFalse()
dispatcher.onBackPressed()
@@ -395,9 +389,8 @@
// is terminal but serves as a good test to make sure the Observer is cleaned up
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START)
assertWithMessage(
- "Previously destroyed callbacks shouldn't appear as an enabled " +
- "dispatcher"
- )
+ "Previously destroyed callbacks shouldn't appear as an enabled " + "dispatcher"
+ )
.that(dispatcher.hasEnabledCallbacks())
.isFalse()
}
@@ -413,9 +406,8 @@
dispatcher.addCallback(lifecycleOwner, lifecycleOnBackPressedCallback)
assertWithMessage(
- "Handler should return false when no OnBackPressedCallbacks " +
- "are registered"
- )
+ "Handler should return false when no OnBackPressedCallbacks " + "are registered"
+ )
.that(dispatcher.hasEnabledCallbacks())
.isFalse()
@@ -423,9 +415,8 @@
// is terminal but serves as a good test to make sure no lingering Observer exists
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START)
assertWithMessage(
- "Previously destroyed callbacks shouldn't appear as an enabled " +
- "dispatcher"
- )
+ "Previously destroyed callbacks shouldn't appear as an enabled " + "dispatcher"
+ )
.that(dispatcher.hasEnabledCallbacks())
.isFalse()
}
@@ -437,7 +428,7 @@
@LargeTest
@Test
fun testCallOnBackPressedWhenStopped() {
- withUse(ActivityScenario.launch(ContentViewActivity::class.java)) {
+ withUse(ActivityScenario.launch(ContentViewActivity::class.java)) {
val realDispatcher = withActivity { onBackPressedDispatcher }
moveToState(Lifecycle.State.CREATED)
withActivity { realDispatcher.onBackPressed() }
@@ -464,80 +455,53 @@
fun testOnHasEnabledCallbacks() {
var reportedHasEnabledCallbacks = false
var reportCount = 0
- val dispatcher = OnBackPressedDispatcher(
- fallbackOnBackPressed = null,
- onHasEnabledCallbacksChanged = {
- reportedHasEnabledCallbacks = it
- reportCount++
- }
- )
+ val dispatcher =
+ OnBackPressedDispatcher(
+ fallbackOnBackPressed = null,
+ onHasEnabledCallbacksChanged = {
+ reportedHasEnabledCallbacks = it
+ reportCount++
+ }
+ )
- assertWithMessage("initial reportCount")
- .that(reportCount)
- .isEqualTo(0)
+ assertWithMessage("initial reportCount").that(reportCount).isEqualTo(0)
assertWithMessage("initial reportedHasEnabledCallbacks")
.that(reportedHasEnabledCallbacks)
.isFalse()
val callbackA = dispatcher.addCallback(enabled = false) {}
- assertWithMessage("reportCount")
- .that(reportCount)
- .isEqualTo(0)
- assertWithMessage("reportedHasEnabledCallbacks")
- .that(reportedHasEnabledCallbacks)
- .isFalse()
+ assertWithMessage("reportCount").that(reportCount).isEqualTo(0)
+ assertWithMessage("reportedHasEnabledCallbacks").that(reportedHasEnabledCallbacks).isFalse()
callbackA.isEnabled = true
- assertWithMessage("reportCount")
- .that(reportCount)
- .isEqualTo(1)
- assertWithMessage("reportedHasEnabledCallbacks")
- .that(reportedHasEnabledCallbacks)
- .isTrue()
+ assertWithMessage("reportCount").that(reportCount).isEqualTo(1)
+ assertWithMessage("reportedHasEnabledCallbacks").that(reportedHasEnabledCallbacks).isTrue()
val callbackB = dispatcher.addCallback {}
- assertWithMessage("reportCount")
- .that(reportCount)
- .isEqualTo(1)
- assertWithMessage("reportedHasEnabledCallbacks")
- .that(reportedHasEnabledCallbacks)
- .isTrue()
+ assertWithMessage("reportCount").that(reportCount).isEqualTo(1)
+ assertWithMessage("reportedHasEnabledCallbacks").that(reportedHasEnabledCallbacks).isTrue()
callbackA.remove()
- assertWithMessage("reportCount")
- .that(reportCount)
- .isEqualTo(1)
- assertWithMessage("reportedHasEnabledCallbacks")
- .that(reportedHasEnabledCallbacks)
- .isTrue()
+ assertWithMessage("reportCount").that(reportCount).isEqualTo(1)
+ assertWithMessage("reportedHasEnabledCallbacks").that(reportedHasEnabledCallbacks).isTrue()
callbackB.remove()
- assertWithMessage("reportCount")
- .that(reportCount)
- .isEqualTo(2)
- assertWithMessage("reportedHasEnabledCallbacks")
- .that(reportedHasEnabledCallbacks)
- .isFalse()
+ assertWithMessage("reportCount").that(reportCount).isEqualTo(2)
+ assertWithMessage("reportedHasEnabledCallbacks").that(reportedHasEnabledCallbacks).isFalse()
dispatcher.addCallback {}
- assertWithMessage("reportCount")
- .that(reportCount)
- .isEqualTo(3)
- assertWithMessage("reportedHasEnabledCallbacks")
- .that(reportedHasEnabledCallbacks)
- .isTrue()
+ assertWithMessage("reportCount").that(reportCount).isEqualTo(3)
+ assertWithMessage("reportedHasEnabledCallbacks").that(reportedHasEnabledCallbacks).isTrue()
}
}
-open class CountingOnBackPressedCallback(
- enabled: Boolean = true
-) : OnBackPressedCallback(enabled) {
+open class CountingOnBackPressedCallback(enabled: Boolean = true) : OnBackPressedCallback(enabled) {
var count = 0
override fun handleOnBackPressed() {
diff --git a/activity/activity/src/androidTest/java/androidx/activity/ViewTreeOnBackPressedDispatcherTest.kt b/activity/activity/src/androidTest/java/androidx/activity/ViewTreeOnBackPressedDispatcherTest.kt
index 004359f..8a947f86 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/ViewTreeOnBackPressedDispatcherTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/ViewTreeOnBackPressedDispatcherTest.kt
@@ -32,12 +32,9 @@
@RunWith(AndroidJUnit4::class)
class ViewTreeOnBackPressedDispatcherTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
- /**
- * Tests that a direct set/get on a single view survives a round trip
- */
+ /** Tests that a direct set/get on a single view survives a round trip */
@Test
fun setGetSameView() {
val v = View(InstrumentationRegistry.getInstrumentation().context)
@@ -53,8 +50,8 @@
}
/**
- * Tests that the owner set on a root of a subhierarchy is seen by both direct children
- * and other descendants
+ * Tests that the owner set on a root of a subhierarchy is seen by both direct children and
+ * other descendants
*/
@Test
fun ancestorOwner() {
@@ -83,8 +80,8 @@
}
/**
- * Tests that a new owner set between a root and a descendant is seen by the descendant
- * instead of the root value
+ * Tests that a new owner set between a root and a descendant is seen by the descendant instead
+ * of the root value
*/
@Test
fun shadowedOwner() {
diff --git a/activity/activity/src/androidTest/java/androidx/activity/contextaware/ContextAwareHelperTest.kt b/activity/activity/src/androidTest/java/androidx/activity/contextaware/ContextAwareHelperTest.kt
index 8cb9336..5fcceb6 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/contextaware/ContextAwareHelperTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/contextaware/ContextAwareHelperTest.kt
@@ -34,15 +34,12 @@
class ContextAwareHelperTest {
private val contextAware = TestContextAware()
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun addOnContextAvailableListener() {
var callbackCount = 0
- val listener = OnContextAvailableListener {
- callbackCount++
- }
+ val listener = OnContextAvailableListener { callbackCount++ }
contextAware.addOnContextAvailableListener(listener)
assertThat(contextAware.peekAvailableContext()).isNull()
contextAware.dispatchOnContextAvailable()
@@ -54,9 +51,7 @@
@Test
fun removeOnContextAvailableListener() {
var callbackCount = 0
- val listener = OnContextAvailableListener {
- callbackCount++
- }
+ val listener = OnContextAvailableListener { callbackCount++ }
contextAware.addOnContextAvailableListener(listener)
contextAware.dispatchOnContextAvailable()
@@ -72,12 +67,13 @@
@Test
fun reentrantRemove() {
var callbackCount = 0
- val listener = object : OnContextAvailableListener {
- override fun onContextAvailable(context: Context) {
- callbackCount++
- contextAware.removeOnContextAvailableListener(this)
+ val listener =
+ object : OnContextAvailableListener {
+ override fun onContextAvailable(context: Context) {
+ callbackCount++
+ contextAware.removeOnContextAvailableListener(this)
+ }
}
- }
contextAware.addOnContextAvailableListener(listener)
contextAware.dispatchOnContextAvailable()
@@ -93,9 +89,7 @@
fun postAvailableAddOnContextAvailableListener() {
contextAware.dispatchOnContextAvailable()
var callbackCount = 0
- val listener = OnContextAvailableListener {
- callbackCount++
- }
+ val listener = OnContextAvailableListener { callbackCount++ }
contextAware.addOnContextAvailableListener(listener)
assertThat(callbackCount).isEqualTo(1)
@@ -106,42 +100,36 @@
contextAware.dispatchOnContextAvailable()
contextAware.clearAvailableContext()
var callbackCount = 0
- val listener = OnContextAvailableListener {
- callbackCount++
- }
+ val listener = OnContextAvailableListener { callbackCount++ }
contextAware.addOnContextAvailableListener(listener)
assertThat(callbackCount).isEqualTo(0)
}
@Test
- fun alreadyAvailable() = runBlocking(Dispatchers.Main) {
- val contextAware = TestContextAware()
- contextAware.dispatchOnContextAvailable()
- var result = "initial"
- val receivedResult = contextAware.withContextAvailable {
- result
+ fun alreadyAvailable() =
+ runBlocking(Dispatchers.Main) {
+ val contextAware = TestContextAware()
+ contextAware.dispatchOnContextAvailable()
+ var result = "initial"
+ val receivedResult = contextAware.withContextAvailable { result }
+ result = "after"
+ assertThat(receivedResult).isEqualTo("initial")
}
- result = "after"
- assertThat(receivedResult).isEqualTo("initial")
- }
@Test
- fun suspending() = runBlocking(Dispatchers.Main) {
- val contextAware = TestContextAware()
- var result = "initial"
- launch {
- contextAware.dispatchOnContextAvailable()
- result = "post dispatch"
+ fun suspending() =
+ runBlocking(Dispatchers.Main) {
+ val contextAware = TestContextAware()
+ var result = "initial"
+ launch {
+ contextAware.dispatchOnContextAvailable()
+ result = "post dispatch"
+ }
+ val receivedResult = contextAware.withContextAvailable { result }
+ contextAware.addOnContextAvailableListener { result = "after" }
+ assertThat(receivedResult).isEqualTo("initial")
}
- val receivedResult = contextAware.withContextAvailable {
- result
- }
- contextAware.addOnContextAvailableListener {
- result = "after"
- }
- assertThat(receivedResult).isEqualTo("initial")
- }
}
class TestContextAware : ContextAware {
@@ -158,9 +146,7 @@
}
fun dispatchOnContextAvailable() {
- contextAwareHelper.dispatchOnContextAvailable(
- ApplicationProvider.getApplicationContext()
- )
+ contextAwareHelper.dispatchOnContextAvailable(ApplicationProvider.getApplicationContext())
}
fun clearAvailableContext() {
diff --git a/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultCallerTest.kt b/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultCallerTest.kt
index a09b453..0752772 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultCallerTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultCallerTest.kt
@@ -45,6 +45,6 @@
class EmptyContentActivity : ComponentActivity() {
val contract = StartActivityForResult()
- val javaLauncher = registerForActivityResult(contract) { }
- val kotlinLauncher = registerForActivityResult(contract, Intent()) { }
+ val javaLauncher = registerForActivityResult(contract) {}
+ val kotlinLauncher = registerForActivityResult(contract, Intent()) {}
}
diff --git a/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultLauncherTest.kt b/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultLauncherTest.kt
index 37d6027..780a772 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultLauncherTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultLauncherTest.kt
@@ -36,23 +36,23 @@
@SmallTest
@RunWith(AndroidJUnit4::class)
class ActivityResultLauncherTest {
- private val registry = object : ActivityResultRegistry() {
- var invokeCount = 0
- var invokeOptions: ActivityOptionsCompat? = null
+ private val registry =
+ object : ActivityResultRegistry() {
+ var invokeCount = 0
+ var invokeOptions: ActivityOptionsCompat? = null
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- invokeCount++
- invokeOptions = options
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ invokeCount++
+ invokeOptions = options
+ }
}
- }
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun launchTest() {
@@ -60,9 +60,7 @@
launcher.launch(Intent())
- assertWithMessage("the registry was not invoked")
- .that(registry.invokeCount)
- .isEqualTo(1)
+ assertWithMessage("the registry was not invoked").that(registry.invokeCount).isEqualTo(1)
assertWithMessage("the options passed to invoke were not null")
.that(registry.invokeOptions)
@@ -72,28 +70,32 @@
@Test
fun launchUnit() {
val expectedResult = "result"
- val registry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- contract.createIntent(InstrumentationRegistry.getInstrumentation().context, input)
- dispatchResult(requestCode, expectedResult)
+ val registry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ contract.createIntent(
+ InstrumentationRegistry.getInstrumentation().context,
+ input
+ )
+ dispatchResult(requestCode, expectedResult)
+ }
}
- }
- val contract = object : ActivityResultContract<Unit, String?>() {
- override fun createIntent(context: Context, input: Unit) = Intent()
- override fun parseResult(resultCode: Int, intent: Intent?) = ""
- }
+ val contract =
+ object : ActivityResultContract<Unit, String?>() {
+ override fun createIntent(context: Context, input: Unit) = Intent()
+
+ override fun parseResult(resultCode: Int, intent: Intent?) = ""
+ }
var actualResult: String? = null
- val launcher = registry.register("key", contract) {
- actualResult = it
- }
+ val launcher = registry.register("key", contract) { actualResult = it }
launcher.launch()
assertThat(actualResult).isEqualTo(expectedResult)
@@ -105,15 +107,11 @@
val launcher = registry.register("key", StartActivityForResult()) {}
val options = ActivityOptionsCompat.makeBasic()
- options.launchBounds = Rect().apply {
- left = 1
- }
+ options.launchBounds = Rect().apply { left = 1 }
launcher.launch(Intent(), options)
- assertWithMessage("the registry was not invoked")
- .that(registry.invokeCount)
- .isEqualTo(1)
+ assertWithMessage("the registry was not invoked").that(registry.invokeCount).isEqualTo(1)
assertWithMessage("the options passed to invoke were null")
.that(registry.invokeOptions)
diff --git a/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultRegistryTest.kt b/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultRegistryTest.kt
index 87cb738..d6a6d27 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultRegistryTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/result/ActivityResultRegistryTest.kt
@@ -39,19 +39,19 @@
@MediumTest
@RunWith(AndroidJUnit4::class)
class ActivityResultRegistryTest {
- private val registry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- dispatchResult(requestCode, RESULT_OK, Intent())
+ private val registry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ dispatchResult(requestCode, RESULT_OK, Intent())
+ }
}
- }
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun testRegisterLifecycleOwnerCallback() {
@@ -59,11 +59,10 @@
var resultReturned = false
// register for the result
- val activityResult = registry.register(
- "test", lifecycleOwner, TakePicturePreview()
- ) {
- resultReturned = true
- }
+ val activityResult =
+ registry.register("test", lifecycleOwner, TakePicturePreview()) {
+ resultReturned = true
+ }
// move the state to started
lifecycleOwner.currentState = Lifecycle.State.STARTED
@@ -79,10 +78,7 @@
val lifecycleOwner = TestLifecycleOwner(Lifecycle.State.CREATED)
// register for the result
- val activityResult = registry.register(
- "test", lifecycleOwner,
- TakePicturePreview()
- ) {}
+ val activityResult = registry.register("test", lifecycleOwner, TakePicturePreview()) {}
// saved the state of the registry
val state = Bundle()
@@ -99,11 +95,7 @@
var resultReturned = false
// re-register for the result that should have been saved
- registry.register(
- "test", lifecycleOwner, TakePicturePreview()
- ) {
- resultReturned = true
- }
+ registry.register("test", lifecycleOwner, TakePicturePreview()) { resultReturned = true }
lifecycleOwner.currentState = Lifecycle.State.STARTED
@@ -116,16 +108,18 @@
try {
// register for the result
- registry.register(
- "test", lifecycleOwner, TakePicturePreview()
- ) {}
+ registry.register("test", lifecycleOwner, TakePicturePreview()) {}
fail("Registering for activity result after Lifecycle ON_CREATE should fail")
} catch (e: IllegalStateException) {
- assertThat(e).hasMessageThat().contains(
- "LifecycleOwner $lifecycleOwner is attempting to register while current state " +
- "is " + lifecycleOwner.currentState + ". LifecycleOwners must call " +
- "register before they are STARTED."
- )
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "LifecycleOwner $lifecycleOwner is attempting to register while current state " +
+ "is " +
+ lifecycleOwner.currentState +
+ ". LifecycleOwners must call " +
+ "register before they are STARTED."
+ )
}
}
@@ -134,9 +128,7 @@
val lifecycleOwner = TestLifecycleOwner(Lifecycle.State.INITIALIZED)
// register for the result
- val activityResult = registry.register(
- "test", lifecycleOwner, TakePicturePreview()
- ) {}
+ val activityResult = registry.register("test", lifecycleOwner, TakePicturePreview()) {}
// saved the state of the registry
val state = Bundle()
@@ -150,11 +142,7 @@
var resultReturned = false
// re-register for the result that should have been saved
- registry.register(
- "test", lifecycleOwner, TakePicturePreview()
- ) {
- resultReturned = true
- }
+ registry.register("test", lifecycleOwner, TakePicturePreview()) { resultReturned = true }
// launch the result
activityResult.launch(null)
@@ -181,23 +169,27 @@
fun testLifecycleOwnerCallbackWithDispatchResult() {
val lifecycleOwner = TestLifecycleOwner(Lifecycle.State.INITIALIZED)
- val dispatchResultRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- dispatchResult(requestCode, true)
+ val dispatchResultRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ dispatchResult(requestCode, true)
+ }
}
- }
var resultReturned = false
- val activityResult = dispatchResultRegistry.register(
- "test", lifecycleOwner, TakePicture(),
- ) {
- resultReturned = true
- }
+ val activityResult =
+ dispatchResultRegistry.register(
+ "test",
+ lifecycleOwner,
+ TakePicture(),
+ ) {
+ resultReturned = true
+ }
// launch the result
activityResult.launch(Uri.EMPTY)
@@ -224,23 +216,27 @@
fun testLifecycleOwnerCallbackWithNullDispatchResult() {
val lifecycleOwner = TestLifecycleOwner(Lifecycle.State.INITIALIZED)
- val dispatchResultRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- dispatchResult(requestCode, null)
+ val dispatchResultRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ dispatchResult(requestCode, null)
+ }
}
- }
var resultReturned = false
- val activityResult = dispatchResultRegistry.register(
- "test", lifecycleOwner, TakePicturePreview(),
- ) {
- resultReturned = true
- }
+ val activityResult =
+ dispatchResultRegistry.register(
+ "test",
+ lifecycleOwner,
+ TakePicturePreview(),
+ ) {
+ resultReturned = true
+ }
// launch the result
activityResult.launch(null)
@@ -268,9 +264,7 @@
val lifecycleOwner = TestLifecycleOwner(Lifecycle.State.INITIALIZED)
// register for the result
- val activityResult = registry.register(
- "test", lifecycleOwner, TakePicturePreview()
- ) {}
+ val activityResult = registry.register("test", lifecycleOwner, TakePicturePreview()) {}
// saved the state of the registry
val state = Bundle()
@@ -287,11 +281,7 @@
var resultReturned = false
// re-register for the result that should have been saved
- registry.register(
- "test", lifecycleOwner, TakePicturePreview()
- ) {
- resultReturned = true
- }
+ registry.register("test", lifecycleOwner, TakePicturePreview()) { resultReturned = true }
// move to CREATED and make sure the callback is not fired
lifecycleOwner.currentState = Lifecycle.State.CREATED
@@ -309,7 +299,7 @@
fun testUnregisterAfterSavedState() {
val lifecycleOwner = TestLifecycleOwner(Lifecycle.State.INITIALIZED)
var resultReturned = false
- val activityResult = registry.register("key", lifecycleOwner, StartActivityForResult()) { }
+ val activityResult = registry.register("key", lifecycleOwner, StartActivityForResult()) {}
activityResult.launch(Intent())
@@ -318,16 +308,17 @@
registry.unregister("key")
- val restoredRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- dispatchResult(requestCode, RESULT_OK, Intent())
+ val restoredRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ dispatchResult(requestCode, RESULT_OK, Intent())
+ }
}
- }
restoredRegistry.onRestoreInstanceState(savedState)
@@ -357,23 +348,24 @@
@Test
fun testRegisterBeforeRestoreInstanceState() {
- registry.register("key", StartActivityForResult()) { }
+ registry.register("key", StartActivityForResult()) {}
val savedState = Bundle()
registry.onSaveInstanceState(savedState)
- val restoredRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- dispatchResult(requestCode, RESULT_OK, Intent())
+ val restoredRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ dispatchResult(requestCode, RESULT_OK, Intent())
+ }
}
- }
- restoredRegistry.register("key", StartActivityForResult()) { }
+ restoredRegistry.register("key", StartActivityForResult()) {}
restoredRegistry.onRestoreInstanceState(savedState)
val newSavedState = Bundle()
@@ -387,26 +379,25 @@
@Test
fun testKeepKeyAfterLaunch() {
var code = 0
- val noDispatchRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- code = requestCode
+ val noDispatchRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ code = requestCode
+ }
}
- }
- val activityResult = noDispatchRegistry.register("key", StartActivityForResult()) { }
+ val activityResult = noDispatchRegistry.register("key", StartActivityForResult()) {}
activityResult.launch(Intent())
activityResult.unregister()
var callbackExecuted = false
- noDispatchRegistry.register("key", StartActivityForResult()) {
- callbackExecuted = true
- }
+ noDispatchRegistry.register("key", StartActivityForResult()) { callbackExecuted = true }
noDispatchRegistry.dispatchResult(code, RESULT_OK, Intent())
@@ -416,26 +407,25 @@
@Test
fun testKeepKeyAfterLaunchDispatchResult() {
var code = 0
- val noDispatchRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- code = requestCode
+ val noDispatchRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ code = requestCode
+ }
}
- }
- val activityResult = noDispatchRegistry.register("key", StartActivityForResult()) { }
+ val activityResult = noDispatchRegistry.register("key", StartActivityForResult()) {}
activityResult.launch(Intent())
activityResult.unregister()
var callbackExecuted = false
- noDispatchRegistry.register("key", StartActivityForResult()) {
- callbackExecuted = true
- }
+ noDispatchRegistry.register("key", StartActivityForResult()) { callbackExecuted = true }
noDispatchRegistry.dispatchResult(code, ActivityResult(RESULT_OK, Intent()))
@@ -445,37 +435,41 @@
@Test
fun testLaunchUnregistered() {
val contract = StartActivityForResult()
- val activityResult = registry.register("key", contract) { }
+ val activityResult = registry.register("key", contract) {}
activityResult.unregister()
try {
activityResult.launch(Intent())
} catch (e: IllegalStateException) {
- assertThat(e).hasMessageThat().contains(
- "Attempting to launch an unregistered ActivityResultLauncher with contract " +
- contract + " and input ${Intent()}. You must ensure the " +
- "ActivityResultLauncher is registered before calling launch()."
- )
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "Attempting to launch an unregistered ActivityResultLauncher with contract " +
+ contract +
+ " and input ${Intent()}. You must ensure the " +
+ "ActivityResultLauncher is registered before calling launch()."
+ )
}
}
@Test
fun testSavePendingOnRestore() {
var code = 0
- val noDispatchRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- code = requestCode
+ val noDispatchRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ code = requestCode
+ }
}
- }
val contract = StartActivityForResult()
- val launcher = noDispatchRegistry.register("key", contract) { }
+ val launcher = noDispatchRegistry.register("key", contract) {}
launcher.launch(Intent())
launcher.unregister()
@@ -485,21 +479,20 @@
val savedState = Bundle()
noDispatchRegistry.onSaveInstanceState(savedState)
- val newNoDispatchRegistry = object : ActivityResultRegistry() {
- override fun <I : Any?, O : Any?> onLaunch(
- requestCode: Int,
- contract: ActivityResultContract<I, O>,
- input: I,
- options: ActivityOptionsCompat?
- ) {
- code = requestCode
+ val newNoDispatchRegistry =
+ object : ActivityResultRegistry() {
+ override fun <I : Any?, O : Any?> onLaunch(
+ requestCode: Int,
+ contract: ActivityResultContract<I, O>,
+ input: I,
+ options: ActivityOptionsCompat?
+ ) {
+ code = requestCode
+ }
}
- }
var completedLaunch = false
- newNoDispatchRegistry.register("key", contract) {
- completedLaunch = true
- }
+ newNoDispatchRegistry.register("key", contract) { completedLaunch = true }
newNoDispatchRegistry.onRestoreInstanceState(savedState)
diff --git a/activity/activity/src/androidTest/java/androidx/activity/result/PickVisualMediaRequestTest.kt b/activity/activity/src/androidTest/java/androidx/activity/result/PickVisualMediaRequestTest.kt
index 4d388bc..0a4d24d 100644
--- a/activity/activity/src/androidTest/java/androidx/activity/result/PickVisualMediaRequestTest.kt
+++ b/activity/activity/src/androidTest/java/androidx/activity/result/PickVisualMediaRequestTest.kt
@@ -29,14 +29,14 @@
@RunWith(AndroidJUnit4::class)
class PickVisualMediaRequestTest {
- @get:Rule
- val rule = DetectLeaksAfterTestSuccess()
+ @get:Rule val rule = DetectLeaksAfterTestSuccess()
@Test
fun buildPickVisualMedia() {
- val request = PickVisualMediaRequest.Builder().setMediaType(
- ActivityResultContracts.PickVisualMedia.VideoOnly
- ).build()
+ val request =
+ PickVisualMediaRequest.Builder()
+ .setMediaType(ActivityResultContracts.PickVisualMedia.VideoOnly)
+ .build()
assertThat(request.mediaType).isEqualTo(ActivityResultContracts.PickVisualMedia.VideoOnly)
}
diff --git a/activity/activity/src/main/java/androidx/activity/ActivityViewModelLazy.kt b/activity/activity/src/main/java/androidx/activity/ActivityViewModelLazy.kt
index b7985fc..afb4cce 100644
--- a/activity/activity/src/main/java/androidx/activity/ActivityViewModelLazy.kt
+++ b/activity/activity/src/main/java/androidx/activity/ActivityViewModelLazy.kt
@@ -24,9 +24,9 @@
import androidx.lifecycle.viewmodel.CreationExtras
/**
- * Returns a [Lazy] delegate to access the ComponentActivity's ViewModel, if [factoryProducer]
- * is specified then [ViewModelProvider.Factory] returned by it will be used
- * to create [ViewModel] first time.
+ * Returns a [Lazy] delegate to access the ComponentActivity's ViewModel, if [factoryProducer] is
+ * specified then [ViewModelProvider.Factory] returned by it will be used to create [ViewModel]
+ * first time.
*
* ```
* class MyComponentActivity : ComponentActivity() {
@@ -34,20 +34,15 @@
* }
* ```
*
- * This property can be accessed only after the Activity is attached to the Application,
- * and access prior to that will result in IllegalArgumentException.
+ * This property can be accessed only after the Activity is attached to the Application, and access
+ * prior to that will result in IllegalArgumentException.
*/
-@Deprecated(
- "Superseded by viewModels that takes a CreationExtras",
- level = DeprecationLevel.HIDDEN
-)
+@Deprecated("Superseded by viewModels that takes a CreationExtras", level = DeprecationLevel.HIDDEN)
@MainThread
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
- val factoryPromise = factoryProducer ?: {
- defaultViewModelProviderFactory
- }
+ val factoryPromise = factoryProducer ?: { defaultViewModelProviderFactory }
return ViewModelLazy(
VM::class,
@@ -58,9 +53,9 @@
}
/**
- * Returns a [Lazy] delegate to access the ComponentActivity's ViewModel, if [factoryProducer]
- * is specified then [ViewModelProvider.Factory] returned by it will be used
- * to create [ViewModel] first time.
+ * Returns a [Lazy] delegate to access the ComponentActivity's ViewModel, if [factoryProducer] is
+ * specified then [ViewModelProvider.Factory] returned by it will be used to create [ViewModel]
+ * first time.
*
* ```
* class MyComponentActivity : ComponentActivity() {
@@ -68,17 +63,15 @@
* }
* ```
*
- * This property can be accessed only after the Activity is attached to the Application,
- * and access prior to that will result in IllegalArgumentException.
+ * This property can be accessed only after the Activity is attached to the Application, and access
+ * prior to that will result in IllegalArgumentException.
*/
@MainThread
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
- val factoryPromise = factoryProducer ?: {
- defaultViewModelProviderFactory
- }
+ val factoryPromise = factoryProducer ?: { defaultViewModelProviderFactory }
return ViewModelLazy(
VM::class,
diff --git a/activity/activity/src/main/java/androidx/activity/BackEventCompat.kt b/activity/activity/src/main/java/androidx/activity/BackEventCompat.kt
index a53c63d..3760f12 100644
--- a/activity/activity/src/main/java/androidx/activity/BackEventCompat.kt
+++ b/activity/activity/src/main/java/androidx/activity/BackEventCompat.kt
@@ -25,13 +25,13 @@
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
-/**
- * Compat around the [BackEvent] class
- */
-class BackEventCompat @VisibleForTesting constructor(
+/** Compat around the [BackEvent] class */
+class BackEventCompat
+@VisibleForTesting
+constructor(
/**
* Absolute X location of the touch point of this event in the coordinate space of the view that
- * * received this back event.
+ * * received this back event.
*/
val touchX: Float,
/**
@@ -39,27 +39,23 @@
* received this back event.
*/
val touchY: Float,
- /**
- * Value between 0 and 1 on how far along the back gesture is.
- */
- @FloatRange(from = 0.0, to = 1.0)
- val progress: Float,
- /**
- * Indicates which edge the swipe starts from.
- */
+ /** Value between 0 and 1 on how far along the back gesture is. */
+ @FloatRange(from = 0.0, to = 1.0) val progress: Float,
+ /** Indicates which edge the swipe starts from. */
val swipeEdge: @SwipeEdge Int
) {
@RequiresApi(34)
- constructor(backEvent: BackEvent) : this (
+ constructor(
+ backEvent: BackEvent
+ ) : this(
Api34Impl.touchX(backEvent),
Api34Impl.touchY(backEvent),
Api34Impl.progress(backEvent),
Api34Impl.swipeEdge(backEvent)
)
- /**
- */
+ /** */
@Target(AnnotationTarget.TYPE)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@Retention(AnnotationRetention.SOURCE)
@@ -70,7 +66,6 @@
* Convert this compat object to [BackEvent] object.
*
* @return [BackEvent] object
- *
* @throws UnsupportedOperationException if this API is called on an API prior to 34.
*/
@RequiresApi(34)
@@ -88,10 +83,10 @@
}
companion object {
- /** Indicates that the edge swipe starts from the left edge of the screen */
+ /** Indicates that the edge swipe starts from the left edge of the screen */
const val EDGE_LEFT = 0
- /** Indicates that the edge swipe starts from the right edge of the screen */
+ /** Indicates that the edge swipe starts from the right edge of the screen */
const val EDGE_RIGHT = 1
}
}
@@ -102,15 +97,11 @@
fun createOnBackEvent(touchX: Float, touchY: Float, progress: Float, swipeEdge: Int) =
BackEvent(touchX, touchY, progress, swipeEdge)
- @DoNotInline
- fun progress(backEvent: BackEvent) = backEvent.progress
+ @DoNotInline fun progress(backEvent: BackEvent) = backEvent.progress
- @DoNotInline
- fun touchX(backEvent: BackEvent) = backEvent.touchX
+ @DoNotInline fun touchX(backEvent: BackEvent) = backEvent.touchX
- @DoNotInline
- fun touchY(backEvent: BackEvent) = backEvent.touchY
+ @DoNotInline fun touchY(backEvent: BackEvent) = backEvent.touchY
- @DoNotInline
- fun swipeEdge(backEvent: BackEvent) = backEvent.swipeEdge
+ @DoNotInline fun swipeEdge(backEvent: BackEvent) = backEvent.swipeEdge
}
diff --git a/activity/activity/src/main/java/androidx/activity/Cancellable.kt b/activity/activity/src/main/java/androidx/activity/Cancellable.kt
index 84dec13..ae96789 100644
--- a/activity/activity/src/main/java/androidx/activity/Cancellable.kt
+++ b/activity/activity/src/main/java/androidx/activity/Cancellable.kt
@@ -15,13 +15,11 @@
*/
package androidx.activity
-/**
- * Token representing a cancellable operation.
- */
+/** Token representing a cancellable operation. */
internal interface Cancellable {
/**
- * Cancel the subscription. This call should be idempotent, making it safe to
- * call multiple times.
+ * Cancel the subscription. This call should be idempotent, making it safe to call multiple
+ * times.
*/
fun cancel()
}
diff --git a/activity/activity/src/main/java/androidx/activity/ComponentActivity.kt b/activity/activity/src/main/java/androidx/activity/ComponentActivity.kt
index 7dbdbd4..b9d20e3 100644
--- a/activity/activity/src/main/java/androidx/activity/ComponentActivity.kt
+++ b/activity/activity/src/main/java/androidx/activity/ComponentActivity.kt
@@ -105,11 +105,12 @@
/**
* Base class for activities that enables composition of higher level components.
*
- * Rather than all functionality being built directly into this class, only the minimal set of
- * lower level building blocks are included. Higher level components can then be used as needed
- * without enforcing a deep Activity class hierarchy or strong coupling between components.
+ * Rather than all functionality being built directly into this class, only the minimal set of lower
+ * level building blocks are included. Higher level components can then be used as needed without
+ * enforcing a deep Activity class hierarchy or strong coupling between components.
*/
-open class ComponentActivity() : androidx.core.app.ComponentActivity(),
+open class ComponentActivity() :
+ androidx.core.app.ComponentActivity(),
ContextAware,
LifecycleOwner,
ViewModelStoreOwner,
@@ -141,15 +142,10 @@
private var _viewModelStore: ViewModelStore? = null
private val reportFullyDrawnExecutor = createFullyDrawnExecutor()
override val fullyDrawnReporter by lazy {
- FullyDrawnReporter(
- reportFullyDrawnExecutor
- ) {
- reportFullyDrawn()
- }
+ FullyDrawnReporter(reportFullyDrawnExecutor) { reportFullyDrawn() }
}
- @LayoutRes
- private var contentLayoutId = 0
+ @LayoutRes private var contentLayoutId = 0
private val nextLocalRequestCode = AtomicInteger()
/**
@@ -172,10 +168,7 @@
val synchronousResult = contract.getSynchronousResult(activity, input)
if (synchronousResult != null) {
Handler(Looper.getMainLooper()).post {
- dispatchResult(
- requestCode,
- synchronousResult.value
- )
+ dispatchResult(requestCode, synchronousResult.value)
}
return
}
@@ -201,21 +194,27 @@
}
ActivityCompat.requestPermissions(activity, permissions, requestCode)
} else if (ACTION_INTENT_SENDER_REQUEST == intent.action) {
- val request = intent.getParcelableExtra<IntentSenderRequest>(
- EXTRA_INTENT_SENDER_REQUEST
- )
+ val request =
+ intent.getParcelableExtra<IntentSenderRequest>(EXTRA_INTENT_SENDER_REQUEST)
try {
// startIntentSenderForResult path
ActivityCompat.startIntentSenderForResult(
- activity, request!!.intentSender,
- requestCode, request.fillInIntent, request.flagsMask,
- request.flagsValues, 0, optionsBundle
+ activity,
+ request!!.intentSender,
+ requestCode,
+ request.fillInIntent,
+ request.flagsMask,
+ request.flagsValues,
+ 0,
+ optionsBundle
)
} catch (e: SendIntentException) {
Handler(Looper.getMainLooper()).post {
dispatchResult(
- requestCode, RESULT_CANCELED,
- Intent().setAction(ACTION_INTENT_SENDER_REQUEST)
+ requestCode,
+ RESULT_CANCELED,
+ Intent()
+ .setAction(ACTION_INTENT_SENDER_REQUEST)
.putExtra(EXTRA_SEND_INTENT_EXCEPTION, e)
)
}
@@ -243,9 +242,8 @@
private var dispatchingOnPictureInPictureModeChanged = false
/**
- * Default constructor for ComponentActivity. All Activities must have a default constructor
- * for API 27 and lower devices or when using the default
- * [android.app.AppComponentFactory].
+ * Default constructor for ComponentActivity. All Activities must have a default constructor for
+ * API 27 and lower devices or when using the default [android.app.AppComponentFactory].
*/
init {
@Suppress("RedundantRequireNotNullCall", "LeakingThis")
@@ -256,49 +254,49 @@
"initialization."
}
@Suppress("LeakingThis")
- lifecycle.addObserver(LifecycleEventObserver { _, event ->
- if (event == Lifecycle.Event.ON_STOP) {
- window?.peekDecorView()?.cancelPendingInputEvents()
- }
- })
- @Suppress("LeakingThis")
- lifecycle.addObserver(LifecycleEventObserver { _, event ->
- if (event == Lifecycle.Event.ON_DESTROY) {
- // Clear out the available context
- contextAwareHelper.clearAvailableContext()
- // And clear the ViewModelStore
- if (!isChangingConfigurations) {
- viewModelStore.clear()
+ lifecycle.addObserver(
+ LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_STOP) {
+ window?.peekDecorView()?.cancelPendingInputEvents()
}
- reportFullyDrawnExecutor.activityDestroyed()
}
- })
+ )
@Suppress("LeakingThis")
- lifecycle.addObserver(object : LifecycleEventObserver {
- override fun onStateChanged(
- source: LifecycleOwner,
- event: Lifecycle.Event
- ) {
- ensureViewModelStore()
- lifecycle.removeObserver(this)
+ lifecycle.addObserver(
+ LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_DESTROY) {
+ // Clear out the available context
+ contextAwareHelper.clearAvailableContext()
+ // And clear the ViewModelStore
+ if (!isChangingConfigurations) {
+ viewModelStore.clear()
+ }
+ reportFullyDrawnExecutor.activityDestroyed()
+ }
}
- })
+ )
+ @Suppress("LeakingThis")
+ lifecycle.addObserver(
+ object : LifecycleEventObserver {
+ override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
+ ensureViewModelStore()
+ lifecycle.removeObserver(this)
+ }
+ }
+ )
savedStateRegistryController.performAttach()
enableSavedStateHandles()
if (Build.VERSION.SDK_INT <= 23) {
- @Suppress("LeakingThis")
- lifecycle.addObserver(ImmLeaksCleaner(this))
+ @Suppress("LeakingThis") lifecycle.addObserver(ImmLeaksCleaner(this))
}
- savedStateRegistry.registerSavedStateProvider(
- ACTIVITY_RESULT_TAG
- ) {
+ savedStateRegistry.registerSavedStateProvider(ACTIVITY_RESULT_TAG) {
val outState = Bundle()
activityResultRegistry.onSaveInstanceState(outState)
outState
}
addOnContextAvailableListener {
- val savedInstanceState = savedStateRegistry
- .consumeRestoredStateForKey(ACTIVITY_RESULT_TAG)
+ val savedInstanceState =
+ savedStateRegistry.consumeRestoredStateForKey(ACTIVITY_RESULT_TAG)
if (savedInstanceState != null) {
activityResultRegistry.onRestoreInstanceState(savedInstanceState)
}
@@ -306,12 +304,11 @@
}
/**
- * Alternate constructor that can be used to provide a default layout
- * that will be inflated as part of `super.onCreate(savedInstanceState)`.
+ * Alternate constructor that can be used to provide a default layout that will be inflated as
+ * part of `super.onCreate(savedInstanceState)`.
*
- * This should generally be called from your constructor that takes no parameters,
- * as is required for API 27 and lower or when using the default
- * [android.app.AppComponentFactory].
+ * This should generally be called from your constructor that takes no parameters, as is
+ * required for API 27 and lower or when using the default [android.app.AppComponentFactory].
*/
@ContentView
constructor(@LayoutRes contentLayoutId: Int) : this() {
@@ -321,8 +318,8 @@
/**
* {@inheritDoc}
*
- * If your ComponentActivity is annotated with [ContentView], this will
- * call [setContentView] for you.
+ * If your ComponentActivity is annotated with [ContentView], this will call [setContentView]
+ * for you.
*/
override fun onCreate(savedInstanceState: Bundle?) {
// Restore the Saved State first so that it is available to
@@ -346,9 +343,8 @@
}
/**
- * Retain all appropriate non-config state. You can NOT
- * override this yourself! Use a [androidx.lifecycle.ViewModel] if you want to
- * retain your own non config state.
+ * Retain all appropriate non-config state. You can NOT override this yourself! Use a
+ * [androidx.lifecycle.ViewModel] if you want to retain your own non config state.
*/
@Suppress("deprecation")
final override fun onRetainNonConfigurationInstance(): Any? {
@@ -373,8 +369,8 @@
}
/**
- * Use this instead of [onRetainNonConfigurationInstance].
- * Retrieve later with [lastCustomNonConfigurationInstance].
+ * Use this instead of [onRetainNonConfigurationInstance]. Retrieve later with
+ * [lastCustomNonConfigurationInstance].
*/
@Deprecated("Use a {@link androidx.lifecycle.ViewModel} to store non config state.")
open fun onRetainCustomNonConfigurationInstance(): Any? {
@@ -383,10 +379,7 @@
@get:Deprecated("Use a {@link androidx.lifecycle.ViewModel} to store non config state.")
open val lastCustomNonConfigurationInstance: Any?
- /**
- * Return the value previously returned from
- * [onRetainCustomNonConfigurationInstance].
- */
+ /** Return the value previously returned from [onRetainCustomNonConfigurationInstance]. */
get() {
val nc = lastNonConfigurationInstance as NonConfigurationInstances?
return nc?.custom
@@ -410,18 +403,15 @@
super.setContentView(view, params)
}
- override fun addContentView(
- view: View?,
- params: ViewGroup.LayoutParams?
- ) {
+ override fun addContentView(view: View?, params: ViewGroup.LayoutParams?) {
initializeViewTreeOwners()
reportFullyDrawnExecutor.viewCreated(window.decorView)
super.addContentView(view, params)
}
/**
- * Sets the view tree owners before setting the content view so that the
- * inflation process and attach listeners will see them already present.
+ * Sets the view tree owners before setting the content view so that the inflation process and
+ * attach listeners will see them already present.
*/
@CallSuper
open fun initializeViewTreeOwners() {
@@ -439,21 +429,16 @@
/**
* {@inheritDoc}
*
- * Any listener added here will receive a callback as part of
- * `super.onCreate()`, but importantly **before** any other
- * logic is done (including calling through to the framework
- * [Activity.onCreate] with the exception of restoring the state
- * of the [savedStateRegistry] for use in your listener.
+ * Any listener added here will receive a callback as part of `super.onCreate()`, but
+ * importantly **before** any other logic is done (including calling through to the framework
+ * [Activity.onCreate] with the exception of restoring the state of the [savedStateRegistry] for
+ * use in your listener.
*/
- final override fun addOnContextAvailableListener(
- listener: OnContextAvailableListener
- ) {
+ final override fun addOnContextAvailableListener(listener: OnContextAvailableListener) {
contextAwareHelper.addOnContextAvailableListener(listener)
}
- final override fun removeOnContextAvailableListener(
- listener: OnContextAvailableListener
- ) {
+ final override fun removeOnContextAvailableListener(listener: OnContextAvailableListener) {
contextAwareHelper.removeOnContextAvailableListener(listener)
}
@@ -515,15 +500,13 @@
/**
* {@inheritDoc}
*
- * Overriding this method is no longer supported and this method will be made
- * `final` in a future version of ComponentActivity. If you do override
- * this method, you *must*:
+ * Overriding this method is no longer supported and this method will be made `final` in a
+ * future version of ComponentActivity. If you do override this method, you *must*:
+ * 1. Return an instance of [LifecycleRegistry]
+ * 1. Lazily initialize your LifecycleRegistry object when this is first called.
*
- * 1. Return an instance of [LifecycleRegistry]
- * 1. Lazily initialize your LifecycleRegistry object when this is first called.
- *
- * Note that this method will be called in the super classes' constructor, before any
- * field initialization or object state creation is complete.
+ * Note that this method will be called in the super classes' constructor, before any field
+ * initialization or object state creation is complete.
*/
override val lifecycle: Lifecycle
get() = super.lifecycle
@@ -532,12 +515,12 @@
/**
* Returns the [ViewModelStore] associated with this activity
*
- * Overriding this method is no longer supported and this method will be made
- * `final` in a future version of ComponentActivity.
+ * Overriding this method is no longer supported and this method will be made `final` in a
+ * future version of ComponentActivity.
*
* @return a [ViewModelStore]
* @throws IllegalStateException if called before the Activity is attached to the
- * Application instance i.e., before onCreate()
+ * Application instance i.e., before onCreate()
*/
get() {
checkNotNull(application) {
@@ -562,11 +545,7 @@
}
override val defaultViewModelProviderFactory: ViewModelProvider.Factory by lazy {
- SavedStateViewModelFactory(
- application,
- this,
- if (intent != null) intent.extras else null
- )
+ SavedStateViewModelFactory(application, this, if (intent != null) intent.extras else null)
}
@get:CallSuper
@@ -574,9 +553,8 @@
/**
* {@inheritDoc}
*
- * The extras of [getIntent] when this is first called will be used as
- * the defaults to any [androidx.lifecycle.SavedStateHandle] passed to a view model
- * created using this extra.
+ * The extras of [getIntent] when this is first called will be used as the defaults to any
+ * [androidx.lifecycle.SavedStateHandle] passed to a view model created using this extra.
*/
get() {
val extras = MutableCreationExtras()
@@ -593,10 +571,9 @@
}
/**
- * Called when the activity has detected the user's press of the back
- * key. The [onBackPressedDispatcher] will be given a
- * chance to handle the back button before the default behavior of
- * [android.app.Activity.onBackPressed] is invoked.
+ * Called when the activity has detected the user's press of the back key. The
+ * [onBackPressedDispatcher] will be given a chance to handle the back button before the default
+ * behavior of [android.app.Activity.onBackPressed] is invoked.
*
* @see onBackPressedDispatcher
*/
@@ -613,59 +590,63 @@
}
/**
- * Retrieve the [OnBackPressedDispatcher] that will be triggered when
- * [onBackPressed] is called.
+ * Retrieve the [OnBackPressedDispatcher] that will be triggered when [onBackPressed] is called.
+ *
* @return The [OnBackPressedDispatcher] associated with this ComponentActivity.
*/
@Suppress("DEPRECATION")
final override val onBackPressedDispatcher: OnBackPressedDispatcher by lazy {
OnBackPressedDispatcher {
- // Calling onBackPressed() on an Activity with its state saved can cause an
- // error on devices on API levels before 26. We catch that specific error
- // and throw all others.
- try {
- [email protected]()
- } catch (e: IllegalStateException) {
- if (e.message != "Can not perform this action after onSaveInstanceState") {
- throw e
- }
- } catch (e: NullPointerException) {
- if (e.message != "Attempt to invoke virtual method 'android.os.Handler " +
- "android.app.FragmentHostCallback.getHandler()' on a " +
- "null object reference") {
- throw e
+ // Calling onBackPressed() on an Activity with its state saved can cause an
+ // error on devices on API levels before 26. We catch that specific error
+ // and throw all others.
+ try {
+ [email protected]()
+ } catch (e: IllegalStateException) {
+ if (e.message != "Can not perform this action after onSaveInstanceState") {
+ throw e
+ }
+ } catch (e: NullPointerException) {
+ if (
+ e.message !=
+ "Attempt to invoke virtual method 'android.os.Handler " +
+ "android.app.FragmentHostCallback.getHandler()' on a " +
+ "null object reference"
+ ) {
+ throw e
+ }
}
}
- }.also { dispatcher ->
- if (Build.VERSION.SDK_INT >= 33) {
- if (Looper.myLooper() != Looper.getMainLooper()) {
- Handler(Looper.getMainLooper()).post {
+ .also { dispatcher ->
+ if (Build.VERSION.SDK_INT >= 33) {
+ if (Looper.myLooper() != Looper.getMainLooper()) {
+ Handler(Looper.getMainLooper()).post {
+ addObserverForBackInvoker(dispatcher)
+ }
+ } else {
addObserverForBackInvoker(dispatcher)
}
- } else {
- addObserverForBackInvoker(dispatcher)
}
}
- }
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun addObserverForBackInvoker(dispatcher: OnBackPressedDispatcher) {
- lifecycle.addObserver(LifecycleEventObserver { _, event ->
- if (event == Lifecycle.Event.ON_CREATE) {
- dispatcher.setOnBackInvokedDispatcher(
- Api33Impl.getOnBackInvokedDispatcher(this@ComponentActivity)
- )
+ lifecycle.addObserver(
+ LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_CREATE) {
+ dispatcher.setOnBackInvokedDispatcher(
+ Api33Impl.getOnBackInvokedDispatcher(this@ComponentActivity)
+ )
+ }
}
- })
+ )
}
final override val savedStateRegistry: SavedStateRegistry
get() = savedStateRegistryController.savedStateRegistry
- /**
- * {@inheritDoc}
- */
+ /** {@inheritDoc} */
@Deprecated(
"""This method has been deprecated in favor of using the Activity Result API
which brings increased type safety via an {@link ActivityResultContract} and the prebuilt
@@ -676,16 +657,11 @@
{@link #registerForActivityResult(ActivityResultContract, ActivityResultCallback)}
passing in a {@link StartActivityForResult} object for the {@link ActivityResultContract}."""
)
- override fun startActivityForResult(
- intent: Intent,
- requestCode: Int
- ) {
+ override fun startActivityForResult(intent: Intent, requestCode: Int) {
super.startActivityForResult(intent, requestCode)
}
- /**
- * {@inheritDoc}
- */
+ /** {@inheritDoc} */
@Deprecated(
"""This method has been deprecated in favor of using the Activity Result API
which brings increased type safety via an {@link ActivityResultContract} and the prebuilt
@@ -696,17 +672,11 @@
{@link #registerForActivityResult(ActivityResultContract, ActivityResultCallback)}
passing in a {@link StartActivityForResult} object for the {@link ActivityResultContract}."""
)
- override fun startActivityForResult(
- intent: Intent,
- requestCode: Int,
- options: Bundle?
- ) {
+ override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
super.startActivityForResult(intent, requestCode, options)
}
- /**
- * {@inheritDoc}
- */
+ /** {@inheritDoc} */
@Deprecated(
"""This method has been deprecated in favor of using the Activity Result API
which brings increased type safety via an {@link ActivityResultContract} and the prebuilt
@@ -718,9 +688,7 @@
passing in a {@link StartIntentSenderForResult} object for the
{@link ActivityResultContract}."""
)
- @Throws(
- SendIntentException::class
- )
+ @Throws(SendIntentException::class)
override fun startIntentSenderForResult(
intent: IntentSender,
requestCode: Int,
@@ -730,14 +698,16 @@
extraFlags: Int
) {
super.startIntentSenderForResult(
- intent, requestCode, fillInIntent, flagsMask, flagsValues,
+ intent,
+ requestCode,
+ fillInIntent,
+ flagsMask,
+ flagsValues,
extraFlags
)
}
- /**
- * {@inheritDoc}
- */
+ /** {@inheritDoc} */
@Deprecated(
"""This method has been deprecated in favor of using the Activity Result API
which brings increased type safety via an {@link ActivityResultContract} and the prebuilt
@@ -749,9 +719,7 @@
passing in a {@link StartIntentSenderForResult} object for the
{@link ActivityResultContract}."""
)
- @Throws(
- SendIntentException::class
- )
+ @Throws(SendIntentException::class)
override fun startIntentSenderForResult(
intent: IntentSender,
requestCode: Int,
@@ -762,14 +730,17 @@
options: Bundle?
) {
super.startIntentSenderForResult(
- intent, requestCode, fillInIntent, flagsMask, flagsValues,
- extraFlags, options
+ intent,
+ requestCode,
+ fillInIntent,
+ flagsMask,
+ flagsValues,
+ extraFlags,
+ options
)
}
- /**
- * {@inheritDoc}
- */
+ /** {@inheritDoc} */
@CallSuper
@Deprecated(
"""This method has been deprecated in favor of using the Activity Result API
@@ -788,9 +759,7 @@
}
}
- /**
- * {@inheritDoc}
- */
+ /** {@inheritDoc} */
@CallSuper
@Deprecated(
"""This method has been deprecated in favor of using the Activity Result API
@@ -808,8 +777,11 @@
permissions: Array<String>,
grantResults: IntArray
) {
- if (!activityResultRegistry.dispatchResult(
- requestCode, RESULT_OK, Intent()
+ if (
+ !activityResultRegistry.dispatchResult(
+ requestCode,
+ RESULT_OK,
+ Intent()
.putExtra(EXTRA_PERMISSIONS, permissions)
.putExtra(EXTRA_PERMISSION_GRANT_RESULTS, grantResults)
)
@@ -826,7 +798,10 @@
callback: ActivityResultCallback<O>
): ActivityResultLauncher<I> {
return registry.register(
- "activity_rq#" + nextLocalRequestCode.getAndIncrement(), this, contract, callback
+ "activity_rq#" + nextLocalRequestCode.getAndIncrement(),
+ this,
+ contract,
+ callback
)
}
@@ -850,15 +825,11 @@
}
}
- final override fun addOnConfigurationChangedListener(
- listener: Consumer<Configuration>
- ) {
+ final override fun addOnConfigurationChangedListener(listener: Consumer<Configuration>) {
onConfigurationChangedListeners.add(listener)
}
- final override fun removeOnConfigurationChangedListener(
- listener: Consumer<Configuration>
- ) {
+ final override fun removeOnConfigurationChangedListener(listener: Consumer<Configuration>) {
onConfigurationChangedListeners.remove(listener)
}
@@ -886,14 +857,10 @@
/**
* {@inheritDoc}
*
- * Dispatches this call to all listeners added via
- * [addOnNewIntentListener].
+ * Dispatches this call to all listeners added via [addOnNewIntentListener].
*/
@CallSuper
- override fun onNewIntent(
- @Suppress("InvalidNullabilityOverride")
- intent: Intent
- ) {
+ override fun onNewIntent(@Suppress("InvalidNullabilityOverride") intent: Intent) {
super.onNewIntent(intent)
for (listener in onNewIntentListeners) {
listener.accept(intent)
@@ -934,10 +901,7 @@
*/
@RequiresApi(api = Build.VERSION_CODES.O)
@CallSuper
- override fun onMultiWindowModeChanged(
- isInMultiWindowMode: Boolean,
- newConfig: Configuration
- ) {
+ override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean, newConfig: Configuration) {
dispatchingOnMultiWindowModeChanged = true
try {
// We can unconditionally call super.onMultiWindowModeChanged() here because this
@@ -986,8 +950,7 @@
/**
* {@inheritDoc}
*
- * Dispatches this call to all listeners added via
- * [addOnPictureInPictureModeChangedListener].
+ * Dispatches this call to all listeners added via [addOnPictureInPictureModeChangedListener].
*/
@RequiresApi(api = Build.VERSION_CODES.O)
@CallSuper
@@ -1005,11 +968,7 @@
dispatchingOnPictureInPictureModeChanged = false
}
for (listener in onPictureInPictureModeChangedListeners) {
- listener.accept(
- PictureInPictureModeChangedInfo(
- isInPictureInPictureMode, newConfig
- )
- )
+ listener.accept(PictureInPictureModeChangedInfo(isInPictureInPictureMode, newConfig))
}
}
@@ -1053,10 +1012,12 @@
}
if (Build.VERSION.SDK_INT > 19) {
super.reportFullyDrawn()
- } else if (Build.VERSION.SDK_INT == 19 && ContextCompat.checkSelfPermission(
- this,
- Manifest.permission.UPDATE_DEVICE_STATS
- ) == PackageManager.PERMISSION_GRANTED
+ } else if (
+ Build.VERSION.SDK_INT == 19 &&
+ ContextCompat.checkSelfPermission(
+ this,
+ Manifest.permission.UPDATE_DEVICE_STATS
+ ) == PackageManager.PERMISSION_GRANTED
) {
// On API 19, the Activity.reportFullyDrawn() method requires the
// UPDATE_DEVICE_STATS permission, otherwise it throws an exception. Instead of
@@ -1084,14 +1045,16 @@
private interface ReportFullyDrawnExecutor : Executor {
fun viewCreated(view: View)
+
fun activityDestroyed()
}
- private inner class ReportFullyDrawnExecutorImpl : ReportFullyDrawnExecutor,
- OnDrawListener, Runnable {
+ private inner class ReportFullyDrawnExecutorImpl :
+ ReportFullyDrawnExecutor, OnDrawListener, Runnable {
val endWatchTimeMillis = SystemClock.uptimeMillis() + 10000
var currentRunnable: Runnable? = null
var onDrawScheduled = false
+
override fun viewCreated(view: View) {
if (!onDrawScheduled) {
onDrawScheduled = true
@@ -1149,8 +1112,8 @@
}
/**
- * Called when we want to remove the OnDrawListener. OnDrawListener can't be removed
- * from within the onDraw() method.
+ * Called when we want to remove the OnDrawListener. OnDrawListener can't be removed from
+ * within the onDraw() method.
*/
override fun run() {
window.decorView.getViewTreeObserver().removeOnDrawListener(this)
diff --git a/activity/activity/src/main/java/androidx/activity/ComponentDialog.kt b/activity/activity/src/main/java/androidx/activity/ComponentDialog.kt
index f6d1c86..83593d6 100644
--- a/activity/activity/src/main/java/androidx/activity/ComponentDialog.kt
+++ b/activity/activity/src/main/java/androidx/activity/ComponentDialog.kt
@@ -33,22 +33,18 @@
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
-/**
- * Base class for dialogs that enables composition of higher level components.
- */
-open class ComponentDialog @JvmOverloads constructor(
- context: Context,
- @StyleRes themeResId: Int = 0
-) : Dialog(context, themeResId),
+/** Base class for dialogs that enables composition of higher level components. */
+open class ComponentDialog
+@JvmOverloads
+constructor(context: Context, @StyleRes themeResId: Int = 0) :
+ Dialog(context, themeResId),
LifecycleOwner,
OnBackPressedDispatcherOwner,
SavedStateRegistryOwner {
private var _lifecycleRegistry: LifecycleRegistry? = null
private val lifecycleRegistry: LifecycleRegistry
- get() = _lifecycleRegistry ?: LifecycleRegistry(this).also {
- _lifecycleRegistry = it
- }
+ get() = _lifecycleRegistry ?: LifecycleRegistry(this).also { _lifecycleRegistry = it }
private val savedStateRegistryController: SavedStateRegistryController =
SavedStateRegistryController.create(this)
@@ -90,9 +86,7 @@
}
@Suppress("DEPRECATION")
- final override val onBackPressedDispatcher = OnBackPressedDispatcher {
- super.onBackPressed()
- }
+ final override val onBackPressedDispatcher = OnBackPressedDispatcher { super.onBackPressed() }
@CallSuper
override fun onBackPressed() {
@@ -120,8 +114,8 @@
}
/**
- * Sets the view tree owners before setting the content view so that the
- * inflation process and attach listeners will see them already present.
+ * Sets the view tree owners before setting the content view so that the inflation process and
+ * attach listeners will see them already present.
*/
@CallSuper
open fun initializeViewTreeOwners() {
diff --git a/activity/activity/src/main/java/androidx/activity/EdgeToEdge.kt b/activity/activity/src/main/java/androidx/activity/EdgeToEdge.kt
index 3b44d1a..4f78044 100644
--- a/activity/activity/src/main/java/androidx/activity/EdgeToEdge.kt
+++ b/activity/activity/src/main/java/androidx/activity/EdgeToEdge.kt
@@ -34,14 +34,12 @@
// The light scrim color used in the platform API 29+
// https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/com/android/internal/policy/DecorView.java;drc=6ef0f022c333385dba2c294e35b8de544455bf19;l=142
-@VisibleForTesting
-internal val DefaultLightScrim = Color.argb(0xe6, 0xFF, 0xFF, 0xFF)
+@VisibleForTesting internal val DefaultLightScrim = Color.argb(0xe6, 0xFF, 0xFF, 0xFF)
// The dark scrim color used in the platform.
// https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/res/res/color/system_bar_background_semi_transparent.xml
// https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/res/remote_color_resources_res/values/colors.xml;l=67
-@VisibleForTesting
-internal val DefaultDarkScrim = Color.argb(0x80, 0x1b, 0x1b, 0x1b)
+@VisibleForTesting internal val DefaultDarkScrim = Color.argb(0x80, 0x1b, 0x1b, 0x1b)
private var Impl: EdgeToEdgeImpl? = null
@@ -75,31 +73,39 @@
val view = window.decorView
val statusBarIsDark = statusBarStyle.detectDarkMode(view.resources)
val navigationBarIsDark = navigationBarStyle.detectDarkMode(view.resources)
- val impl = Impl ?: if (Build.VERSION.SDK_INT >= 30) {
- EdgeToEdgeApi30()
- } else if (Build.VERSION.SDK_INT >= 29) {
- EdgeToEdgeApi29()
- } else if (Build.VERSION.SDK_INT >= 28) {
- EdgeToEdgeApi28()
- } else if (Build.VERSION.SDK_INT >= 26) {
- EdgeToEdgeApi26()
- } else if (Build.VERSION.SDK_INT >= 23) {
- EdgeToEdgeApi23()
- } else if (Build.VERSION.SDK_INT >= 21) {
- EdgeToEdgeApi21()
- } else {
- EdgeToEdgeBase()
- }.also { Impl = it }
+ val impl =
+ Impl
+ ?: if (Build.VERSION.SDK_INT >= 30) {
+ EdgeToEdgeApi30()
+ } else if (Build.VERSION.SDK_INT >= 29) {
+ EdgeToEdgeApi29()
+ } else if (Build.VERSION.SDK_INT >= 28) {
+ EdgeToEdgeApi28()
+ } else if (Build.VERSION.SDK_INT >= 26) {
+ EdgeToEdgeApi26()
+ } else if (Build.VERSION.SDK_INT >= 23) {
+ EdgeToEdgeApi23()
+ } else
+ if (Build.VERSION.SDK_INT >= 21) {
+ EdgeToEdgeApi21()
+ } else {
+ EdgeToEdgeBase()
+ }
+ .also { Impl = it }
impl.setUp(
- statusBarStyle, navigationBarStyle, window, view, statusBarIsDark, navigationBarIsDark
+ statusBarStyle,
+ navigationBarStyle,
+ window,
+ view,
+ statusBarIsDark,
+ navigationBarIsDark
)
impl.adjustLayoutInDisplayCutoutMode(window)
}
-/**
- * The style for the status bar or the navigation bar used in [enableEdgeToEdge].
- */
-class SystemBarStyle private constructor(
+/** The style for the status bar or the navigation bar used in [enableEdgeToEdge]. */
+class SystemBarStyle
+private constructor(
private val lightScrim: Int,
internal val darkScrim: Int,
internal val nightMode: Int,
@@ -118,14 +124,15 @@
* scrim. This scrim color is provided by the platform and *cannot be customized*.
* - On API level 28 and below, the status bar will be transparent, and the navigation bar
* will have one of the specified scrim colors depending on the dark mode.
+ *
* @param lightScrim The scrim color to be used for the background when the app is in light
- * mode. Note that this is used only on API level 28 and below.
+ * mode. Note that this is used only on API level 28 and below.
* @param darkScrim The scrim color to be used for the background when the app is in dark
- * mode. This is also used on devices where the system icon color is always light. Note that
- * this is used only on API level 28 and below.
+ * mode. This is also used on devices where the system icon color is always light. Note
+ * that this is used only on API level 28 and below.
* @param detectDarkMode Optional. Detects whether UI currently uses dark mode or not. The
- * default implementation can detect any of the standard dark mode features from the
- * platform, appcompat, and Jetpack Compose.
+ * default implementation can detect any of the standard dark mode features from the
+ * platform, appcompat, and Jetpack Compose.
*/
@JvmStatic
@JvmOverloads
@@ -149,8 +156,8 @@
* Creates a new instance of [SystemBarStyle]. This style consistently applies the specified
* scrim color regardless of the system navigation mode.
*
- * @param scrim The scrim color to be used for the background. It is expected to be dark
- * for the contrast against the light system icons.
+ * @param scrim The scrim color to be used for the background. It is expected to be dark for
+ * the contrast against the light system icons.
*/
@JvmStatic
fun dark(@ColorInt scrim: Int): SystemBarStyle {
@@ -167,9 +174,9 @@
* scrim color regardless of the system navigation mode.
*
* @param scrim The scrim color to be used for the background. It is expected to be light
- * for the contrast against the dark system icons.
+ * for the contrast against the dark system icons.
* @param darkScrim The scrim color to be used for the background on devices where the
- * system icon color is always light. It is expected to be dark.
+ * system icon color is always light. It is expected to be dark.
*/
@JvmStatic
fun light(@ColorInt scrim: Int, @ColorInt darkScrim: Int): SystemBarStyle {
diff --git a/activity/activity/src/main/java/androidx/activity/FullyDrawnReporter.kt b/activity/activity/src/main/java/androidx/activity/FullyDrawnReporter.kt
index dd87c18..44e32bf 100644
--- a/activity/activity/src/main/java/androidx/activity/FullyDrawnReporter.kt
+++ b/activity/activity/src/main/java/androidx/activity/FullyDrawnReporter.kt
@@ -21,11 +21,10 @@
import java.util.concurrent.Executor
/**
- * Manages when to call [Activity.reportFullyDrawn]. Different parts of the UI may
- * individually indicate when they are ready for interaction. [Activity.reportFullyDrawn]
- * will only be called by this class when all parts are ready. At least one [addReporter] or
- * [reportWhenComplete] must be used before [Activity.reportFullyDrawn] will be called
- * by this class.
+ * Manages when to call [Activity.reportFullyDrawn]. Different parts of the UI may individually
+ * indicate when they are ready for interaction. [Activity.reportFullyDrawn] will only be called by
+ * this class when all parts are ready. At least one [addReporter] or [reportWhenComplete] must be
+ * used before [Activity.reportFullyDrawn] will be called by this class.
*
* For example, to use coroutines:
* ```
@@ -37,6 +36,7 @@
* }
* }
* ```
+ *
* Or it can be manually controlled:
* ```
* // On the UI thread:
@@ -49,32 +49,25 @@
* @param executor The [Executor] on which to call [reportFullyDrawn].
* @param reportFullyDrawn Will be called when all reporters have been removed.
*/
-class FullyDrawnReporter(
- private val executor: Executor,
- private val reportFullyDrawn: () -> Unit
-) {
+class FullyDrawnReporter(private val executor: Executor, private val reportFullyDrawn: () -> Unit) {
private val lock = Any()
- @GuardedBy("lock")
- private var reporterCount = 0
+ @GuardedBy("lock") private var reporterCount = 0
- @GuardedBy("lock")
- private var reportPosted = false
+ @GuardedBy("lock") private var reportPosted = false
- @GuardedBy("lock")
- private var reportedFullyDrawn = false
+ @GuardedBy("lock") private var reportedFullyDrawn = false
/**
- * Returns `true` after [reportFullyDrawn] has been called or if backed by a
- * [ComponentActivity] and [ComponentActivity.reportFullyDrawn] has been called.
+ * Returns `true` after [reportFullyDrawn] has been called or if backed by a [ComponentActivity]
+ * and [ComponentActivity.reportFullyDrawn] has been called.
*/
val isFullyDrawnReported: Boolean
get() {
return synchronized(lock) { reportedFullyDrawn }
}
- @GuardedBy("lock")
- private val onReportCallbacks = mutableListOf<() -> Unit>()
+ @GuardedBy("lock") private val onReportCallbacks = mutableListOf<() -> Unit>()
private val reportRunnable: Runnable = Runnable {
synchronized(lock) {
@@ -86,9 +79,7 @@
}
}
- /**
- * Adds a lock to prevent calling [reportFullyDrawn].
- */
+ /** Adds a lock to prevent calling [reportFullyDrawn]. */
fun addReporter() {
synchronized(lock) {
if (!reportedFullyDrawn) {
@@ -98,8 +89,8 @@
}
/**
- * Removes a lock added in [addReporter]. When all locks have been removed,
- * [reportFullyDrawn] will be called on the next animation frame.
+ * Removes a lock added in [addReporter]. When all locks have been removed, [reportFullyDrawn]
+ * will be called on the next animation frame.
*/
fun removeReporter() {
synchronized(lock) {
@@ -111,11 +102,11 @@
}
/**
- * Registers [callback] to be called when [reportFullyDrawn] is called by this class.
- * If it has already been called, then [callback] will be called immediately.
+ * Registers [callback] to be called when [reportFullyDrawn] is called by this class. If it has
+ * already been called, then [callback] will be called immediately.
*
- * Once [callback] has been called, it will be removed and [removeOnReportDrawnListener]
- * does not need to be called to remove it.
+ * Once [callback] has been called, it will be removed and [removeOnReportDrawnListener] does
+ * not need to be called to remove it.
*/
fun addOnReportDrawnListener(callback: () -> Unit) {
val callImmediately =
@@ -133,19 +124,17 @@
}
/**
- * Removes a previously registered [callback] so that it won't be called when
- * [reportFullyDrawn] is called by this class.
+ * Removes a previously registered [callback] so that it won't be called when [reportFullyDrawn]
+ * is called by this class.
*/
fun removeOnReportDrawnListener(callback: () -> Unit) {
- synchronized(lock) {
- onReportCallbacks -= callback
- }
+ synchronized(lock) { onReportCallbacks -= callback }
}
/**
* Must be called when when [reportFullyDrawn] is called to indicate that
- * [Activity.reportFullyDrawn] has been called. This method should also be called
- * if [Activity.reportFullyDrawn] has been called outside of this class.
+ * [Activity.reportFullyDrawn] has been called. This method should also be called if
+ * [Activity.reportFullyDrawn] has been called outside of this class.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun fullyDrawnReported() {
@@ -157,9 +146,9 @@
}
/**
- * Posts a request to report that the Activity is fully drawn on the next animation frame.
- * On the next animation frame, it will check again that there are no other reporters
- * that have yet to complete.
+ * Posts a request to report that the Activity is fully drawn on the next animation frame. On
+ * the next animation frame, it will check again that there are no other reporters that have yet
+ * to complete.
*/
private fun postWhenReportersAreDone() {
if (!reportPosted && reporterCount == 0) {
@@ -170,12 +159,11 @@
}
/**
- * Tells the [FullyDrawnReporter] to wait until [reporter] has completed
- * before calling [Activity.reportFullyDrawn].
+ * Tells the [FullyDrawnReporter] to wait until [reporter] has completed before calling
+ * [Activity.reportFullyDrawn].
*/
suspend inline fun FullyDrawnReporter.reportWhenComplete(
- @Suppress("REDUNDANT_INLINE_SUSPEND_FUNCTION_TYPE")
- reporter: suspend () -> Unit
+ @Suppress("REDUNDANT_INLINE_SUSPEND_FUNCTION_TYPE") reporter: suspend () -> Unit
) {
addReporter()
if (isFullyDrawnReported) {
diff --git a/activity/activity/src/main/java/androidx/activity/FullyDrawnReporterOwner.kt b/activity/activity/src/main/java/androidx/activity/FullyDrawnReporterOwner.kt
index ec6af730..302f63d 100644
--- a/activity/activity/src/main/java/androidx/activity/FullyDrawnReporterOwner.kt
+++ b/activity/activity/src/main/java/androidx/activity/FullyDrawnReporterOwner.kt
@@ -16,13 +16,13 @@
package androidx.activity
/**
- * A class that has a [FullyDrawnReporter] that allows you to have separate parts of the
- * UI independently register when they have been fully loaded.
+ * A class that has a [FullyDrawnReporter] that allows you to have separate parts of the UI
+ * independently register when they have been fully loaded.
*/
interface FullyDrawnReporterOwner {
/**
- * Retrieve the [FullyDrawnReporter] that should handle the independent parts of the UI
- * that separately report that they are fully drawn.
+ * Retrieve the [FullyDrawnReporter] that should handle the independent parts of the UI that
+ * separately report that they are fully drawn.
*/
val fullyDrawnReporter: FullyDrawnReporter
}
diff --git a/activity/activity/src/main/java/androidx/activity/ImmLeaksCleaner.kt b/activity/activity/src/main/java/androidx/activity/ImmLeaksCleaner.kt
index 8c3d942..3273c29 100644
--- a/activity/activity/src/main/java/androidx/activity/ImmLeaksCleaner.kt
+++ b/activity/activity/src/main/java/androidx/activity/ImmLeaksCleaner.kt
@@ -34,15 +34,17 @@
activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
with(cleaner) {
val lock = inputMethodManager.lock ?: return
- val success = synchronized(lock) {
- val servedView = inputMethodManager.servedView ?: return
- if (servedView.isAttachedToWindow) {
- return
+ val success =
+ synchronized(lock) {
+ val servedView = inputMethodManager.servedView ?: return
+ if (servedView.isAttachedToWindow) {
+ return
+ }
+ // Here we have a detached mServedView. Set null to mNextServedViewField so
+ // that
+ // everything will be cleared in the next InputMethodManager#checkFocus().
+ inputMethodManager.clearNextServedView()
}
- // Here we have a detached mServedView. Set null to mNextServedViewField so that
- // everything will be cleared in the next InputMethodManager#checkFocus().
- inputMethodManager.clearNextServedView()
- }
if (success) {
// Assume that InputMethodManager#isActive() internally triggers
// InputMethodManager#checkFocus().
@@ -56,16 +58,11 @@
abstract val InputMethodManager.servedView: View?
- /**
- * @return Whether the next served view was successfully cleared
- */
+ /** @return Whether the next served view was successfully cleared */
abstract fun InputMethodManager.clearNextServedView(): Boolean
}
- /**
- * Cleaner that is used when reading the [InputMethodManager] fields via
- * reflection failed.
- */
+ /** Cleaner that is used when reading the [InputMethodManager] fields via reflection failed. */
object FailedInitialization : Cleaner() {
override val InputMethodManager.lock: Any?
get() = null
@@ -76,36 +73,37 @@
override fun InputMethodManager.clearNextServedView(): Boolean = false
}
- /**
- * Cleaner that provides access to hidden fields via reflection
- */
+ /** Cleaner that provides access to hidden fields via reflection */
class ValidCleaner(
private val hField: Field,
private val servedViewField: Field,
private val nextServedViewField: Field,
) : Cleaner() {
override val InputMethodManager.lock: Any?
- get() = try {
- hField.get(this)
- } catch (e: IllegalAccessException) {
- null
- }
+ get() =
+ try {
+ hField.get(this)
+ } catch (e: IllegalAccessException) {
+ null
+ }
override val InputMethodManager.servedView: View?
- get() = try {
- servedViewField.get(this) as View?
- } catch (e: IllegalAccessException) {
- null
- } catch (e: ClassCastException) {
- null
- }
+ get() =
+ try {
+ servedViewField.get(this) as View?
+ } catch (e: IllegalAccessException) {
+ null
+ } catch (e: ClassCastException) {
+ null
+ }
- override fun InputMethodManager.clearNextServedView() = try {
- nextServedViewField.set(this, null)
- true
- } catch (e: IllegalAccessException) {
- false
- }
+ override fun InputMethodManager.clearNextServedView() =
+ try {
+ nextServedViewField.set(this, null)
+ true
+ } catch (e: IllegalAccessException) {
+ false
+ }
}
@SuppressLint("SoonBlockedPrivateApi") // This class is only used API <=23
@@ -113,15 +111,11 @@
val cleaner by lazy {
try {
val immClass = InputMethodManager::class.java
- val servedViewField = immClass.getDeclaredField("mServedView").apply {
- isAccessible = true
- }
- val nextServedViewField = immClass.getDeclaredField("mNextServedView").apply {
- isAccessible = true
- }
- val hField = immClass.getDeclaredField("mH").apply {
- isAccessible = true
- }
+ val servedViewField =
+ immClass.getDeclaredField("mServedView").apply { isAccessible = true }
+ val nextServedViewField =
+ immClass.getDeclaredField("mNextServedView").apply { isAccessible = true }
+ val hField = immClass.getDeclaredField("mH").apply { isAccessible = true }
ValidCleaner(hField, servedViewField, nextServedViewField)
} catch (e: NoSuchFieldException) {
// very oem much custom ¯\_(ツ)_/¯
diff --git a/activity/activity/src/main/java/androidx/activity/OnBackPressedCallback.kt b/activity/activity/src/main/java/androidx/activity/OnBackPressedCallback.kt
index 69038fe..806143d 100644
--- a/activity/activity/src/main/java/androidx/activity/OnBackPressedCallback.kt
+++ b/activity/activity/src/main/java/androidx/activity/OnBackPressedCallback.kt
@@ -19,34 +19,31 @@
import java.util.concurrent.CopyOnWriteArrayList
/**
- * Class for handling [OnBackPressedDispatcher.onBackPressed] callbacks without
- * strongly coupling that implementation to a subclass of [ComponentActivity].
+ * Class for handling [OnBackPressedDispatcher.onBackPressed] callbacks without strongly coupling
+ * that implementation to a subclass of [ComponentActivity].
*
- * This class maintains its own [enabled state][isEnabled]. Only when this callback
- * is enabled will it receive callbacks to [handleOnBackPressed].
+ * This class maintains its own [enabled state][isEnabled]. Only when this callback is enabled will
+ * it receive callbacks to [handleOnBackPressed].
*
* Note that the enabled state is an additional layer on top of the
- * [androidx.lifecycle.LifecycleOwner] passed to
- * [OnBackPressedDispatcher.addCallback]
- * which controls when the callback is added and removed to the dispatcher.
+ * [androidx.lifecycle.LifecycleOwner] passed to [OnBackPressedDispatcher.addCallback] which
+ * controls when the callback is added and removed to the dispatcher.
*
- * By calling [remove], this callback will be removed from any
- * [OnBackPressedDispatcher] it has been added to. It is strongly recommended
- * to instead disable this callback to handle temporary changes in state.
+ * By calling [remove], this callback will be removed from any [OnBackPressedDispatcher] it has been
+ * added to. It is strongly recommended to instead disable this callback to handle temporary changes
+ * in state.
*
* @param enabled The default enabled state for this callback.
- *
* @see OnBackPressedDispatcher
*/
abstract class OnBackPressedCallback(enabled: Boolean) {
/**
- * The enabled state of the callback. Only when this callback
- * is enabled will it receive callbacks to [handleOnBackPressed].
+ * The enabled state of the callback. Only when this callback is enabled will it receive
+ * callbacks to [handleOnBackPressed].
*
* Note that the enabled state is an additional layer on top of the
- * [androidx.lifecycle.LifecycleOwner] passed to
- * [OnBackPressedDispatcher.addCallback]
- * which controls when the callback is added and removed to the dispatcher.
+ * [androidx.lifecycle.LifecycleOwner] passed to [OnBackPressedDispatcher.addCallback] which
+ * controls when the callback is added and removed to the dispatcher.
*/
@get:MainThread
@set:MainThread
@@ -59,12 +56,8 @@
private val cancellables = CopyOnWriteArrayList<Cancellable>()
internal var enabledChangedCallback: (() -> Unit)? = null
- /**
- * Removes this callback from any [OnBackPressedDispatcher] it is currently
- * added to.
- */
- @MainThread
- fun remove() = cancellables.forEach { it.cancel() }
+ /** Removes this callback from any [OnBackPressedDispatcher] it is currently added to. */
+ @MainThread fun remove() = cancellables.forEach { it.cancel() }
/**
* Callback for handling the system UI generated equivalent to
@@ -86,11 +79,8 @@
@MainThread
open fun handleOnBackProgressed(backEvent: BackEventCompat) {}
- /**
- * Callback for handling the [OnBackPressedDispatcher.onBackPressed] event.
- */
- @MainThread
- abstract fun handleOnBackPressed()
+ /** Callback for handling the [OnBackPressedDispatcher.onBackPressed] event. */
+ @MainThread abstract fun handleOnBackPressed()
/**
* Callback for handling the system UI generated equivalent to
diff --git a/activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcher.kt b/activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcher.kt
index 094d95e..cec1a37 100644
--- a/activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcher.kt
+++ b/activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcher.kt
@@ -30,8 +30,8 @@
import androidx.lifecycle.LifecycleOwner
/**
- * Dispatcher that can be used to register [OnBackPressedCallback] instances for handling
- * the [ComponentActivity.onBackPressed] callback via composition.
+ * Dispatcher that can be used to register [OnBackPressedCallback] instances for handling the
+ * [ComponentActivity.onBackPressed] callback via composition.
*
* ```
* class FormEntryFragment : Fragment() {
@@ -52,15 +52,16 @@
* }
* ```
*
- * When constructing an instance of this class, the [fallbackOnBackPressed] can be set to
- * receive a callback if [onBackPressed] is called when [hasEnabledCallbacks] returns `false`.
+ * When constructing an instance of this class, the [fallbackOnBackPressed] can be set to receive a
+ * callback if [onBackPressed] is called when [hasEnabledCallbacks] returns `false`.
*/
// Implementation/API compatibility note: previous releases included only the Runnable? constructor,
// which permitted both first-argument and trailing lambda call syntax to specify
// fallbackOnBackPressed. To avoid silently breaking source compatibility the new
// primary constructor has no optional parameters to avoid ambiguity/wrong overload resolution
// when a single parameter is provided as a trailing lambda.
-class OnBackPressedDispatcher constructor(
+class OnBackPressedDispatcher
+constructor(
private val fallbackOnBackPressed: Runnable?,
private val onHasEnabledCallbacksChanged: Consumer<Boolean>?
) {
@@ -72,9 +73,7 @@
private var hasEnabledCallbacks = false
@JvmOverloads
- constructor(
- fallbackOnBackPressed: Runnable? = null
- ) : this(fallbackOnBackPressed, null)
+ constructor(fallbackOnBackPressed: Runnable? = null) : this(fallbackOnBackPressed, null)
/**
* Sets the [OnBackInvokedDispatcher] for handling system back for Android SDK T+.
@@ -100,10 +99,7 @@
)
backInvokedCallbackRegistered = true
} else if (!shouldBeRegistered && backInvokedCallbackRegistered) {
- Api33Impl.unregisterOnBackInvokedCallback(
- dispatcher,
- onBackInvokedCallback
- )
+ Api33Impl.unregisterOnBackInvokedCallback(dispatcher, onBackInvokedCallback)
backInvokedCallbackRegistered = false
}
}
@@ -123,31 +119,30 @@
init {
if (Build.VERSION.SDK_INT >= 33) {
- onBackInvokedCallback = if (Build.VERSION.SDK_INT >= 34) {
- Api34Impl.createOnBackAnimationCallback(
- { backEvent -> onBackStarted(backEvent) },
- { backEvent -> onBackProgressed(backEvent) },
- { onBackPressed() },
- { onBackCancelled() }
- )
- } else {
- Api33Impl.createOnBackInvokedCallback { onBackPressed() }
- }
+ onBackInvokedCallback =
+ if (Build.VERSION.SDK_INT >= 34) {
+ Api34Impl.createOnBackAnimationCallback(
+ { backEvent -> onBackStarted(backEvent) },
+ { backEvent -> onBackProgressed(backEvent) },
+ { onBackPressed() },
+ { onBackCancelled() }
+ )
+ } else {
+ Api33Impl.createOnBackInvokedCallback { onBackPressed() }
+ }
}
}
/**
- * Add a new [OnBackPressedCallback]. Callbacks are invoked in the reverse order in which
- * they are added, so this newly added [OnBackPressedCallback] will be the first
- * callback to receive a callback if [onBackPressed] is called.
+ * Add a new [OnBackPressedCallback]. Callbacks are invoked in the reverse order in which they
+ * are added, so this newly added [OnBackPressedCallback] will be the first callback to receive
+ * a callback if [onBackPressed] is called.
*
- * This method is **not** [Lifecycle] aware - if you'd like to ensure that
- * you only get callbacks when at least [started][Lifecycle.State.STARTED], use
- * [addCallback]. It is expected that you
- * call [OnBackPressedCallback.remove] to manually remove your callback.
+ * This method is **not** [Lifecycle] aware - if you'd like to ensure that you only get
+ * callbacks when at least [started][Lifecycle.State.STARTED], use [addCallback]. It is expected
+ * that you call [OnBackPressedCallback.remove] to manually remove your callback.
*
* @param onBackPressedCallback The callback to add
- *
* @see onBackPressed
*/
@MainThread
@@ -156,14 +151,13 @@
}
/**
- * Internal implementation of [addCallback] that gives
- * access to the [Cancellable] that specifically removes this callback from
- * the dispatcher without relying on [OnBackPressedCallback.remove] which
- * is what external developers should be using.
+ * Internal implementation of [addCallback] that gives access to the [Cancellable] that
+ * specifically removes this callback from the dispatcher without relying on
+ * [OnBackPressedCallback.remove] which is what external developers should be using.
*
* @param onBackPressedCallback The callback to add
- * @return a [Cancellable] which can be used to [cancel][Cancellable.cancel]
- * the callback and remove it from the set of OnBackPressedCallbacks.
+ * @return a [Cancellable] which can be used to [cancel][Cancellable.cancel] the callback and
+ * remove it from the set of OnBackPressedCallbacks.
*/
@MainThread
internal fun addCancellableCallback(onBackPressedCallback: OnBackPressedCallback): Cancellable {
@@ -176,32 +170,28 @@
}
/**
- * Receive callbacks to a new [OnBackPressedCallback] when the given
- * [LifecycleOwner] is at least [started][Lifecycle.State.STARTED].
+ * Receive callbacks to a new [OnBackPressedCallback] when the given [LifecycleOwner] is at
+ * least [started][Lifecycle.State.STARTED].
*
- * This will automatically call [addCallback] and remove the callback as the lifecycle
- * state changes. As a corollary, if your lifecycle is already at least
- * [started][Lifecycle.State.STARTED], calling this method will result in an immediate
- * call to [addCallback].
+ * This will automatically call [addCallback] and remove the callback as the lifecycle state
+ * changes. As a corollary, if your lifecycle is already at least
+ * [started][Lifecycle.State.STARTED], calling this method will result in an immediate call to
+ * [addCallback].
*
- * When the [LifecycleOwner] is [destroyed][Lifecycle.State.DESTROYED], it will
- * automatically be removed from the list of callbacks. The only time you would need to
- * manually call [OnBackPressedCallback.remove] is if
- * you'd like to remove the callback prior to destruction of the associated lifecycle.
+ * When the [LifecycleOwner] is [destroyed][Lifecycle.State.DESTROYED], it will automatically be
+ * removed from the list of callbacks. The only time you would need to manually call
+ * [OnBackPressedCallback.remove] is if you'd like to remove the callback prior to destruction
+ * of the associated lifecycle.
*
- * If the Lifecycle is already [destroyed][Lifecycle.State.DESTROYED]
- * when this method is called, the callback will not be added.
+ * If the Lifecycle is already [destroyed][Lifecycle.State.DESTROYED] when this method is
+ * called, the callback will not be added.
*
* @param owner The LifecycleOwner which controls when the callback should be invoked
* @param onBackPressedCallback The callback to add
- *
* @see onBackPressed
*/
@MainThread
- fun addCallback(
- owner: LifecycleOwner,
- onBackPressedCallback: OnBackPressedCallback
- ) {
+ fun addCallback(owner: LifecycleOwner, onBackPressedCallback: OnBackPressedCallback) {
val lifecycle = owner.lifecycle
if (lifecycle.currentState === Lifecycle.State.DESTROYED) {
return
@@ -214,13 +204,12 @@
}
/**
- * Returns `true` if there is at least one [enabled][OnBackPressedCallback.isEnabled]
- * callback registered with this dispatcher.
+ * Returns `true` if there is at least one [enabled][OnBackPressedCallback.isEnabled] callback
+ * registered with this dispatcher.
*
* @return True if there is at least one enabled callback.
*/
- @MainThread
- fun hasEnabledCallbacks(): Boolean = hasEnabledCallbacks
+ @MainThread fun hasEnabledCallbacks(): Boolean = hasEnabledCallbacks
@VisibleForTesting
@MainThread
@@ -230,9 +219,7 @@
@MainThread
private fun onBackStarted(backEvent: BackEventCompat) {
- val callback = onBackPressedCallbacks.lastOrNull {
- it.isEnabled
- }
+ val callback = onBackPressedCallbacks.lastOrNull { it.isEnabled }
if (inProgressCallback != null) {
onBackCancelled()
}
@@ -251,9 +238,7 @@
@MainThread
private fun onBackProgressed(backEvent: BackEventCompat) {
- val callback = inProgressCallback ?: onBackPressedCallbacks.lastOrNull {
- it.isEnabled
- }
+ val callback = inProgressCallback ?: onBackPressedCallbacks.lastOrNull { it.isEnabled }
if (callback != null) {
callback.handleOnBackProgressed(backEvent)
return
@@ -261,19 +246,16 @@
}
/**
- * Trigger a call to the currently added [callbacks][OnBackPressedCallback] in reverse
- * order in which they were added. Only if the most recently added callback is not
- * [enabled][OnBackPressedCallback.isEnabled]
- * will any previously added callback be called.
+ * Trigger a call to the currently added [callbacks][OnBackPressedCallback] in reverse order in
+ * which they were added. Only if the most recently added callback is not
+ * [enabled][OnBackPressedCallback.isEnabled] will any previously added callback be called.
*
- * If [hasEnabledCallbacks] is `false` when this method is called, the
- * [fallbackOnBackPressed] set by the constructor will be triggered.
+ * If [hasEnabledCallbacks] is `false` when this method is called, the [fallbackOnBackPressed]
+ * set by the constructor will be triggered.
*/
@MainThread
fun onBackPressed() {
- val callback = inProgressCallback ?: onBackPressedCallbacks.lastOrNull {
- it.isEnabled
- }
+ val callback = inProgressCallback ?: onBackPressedCallbacks.lastOrNull { it.isEnabled }
inProgressCallback = null
if (callback != null) {
callback.handleOnBackPressed()
@@ -290,9 +272,7 @@
@MainThread
private fun onBackCancelled() {
- val callback = inProgressCallback ?: onBackPressedCallbacks.lastOrNull {
- it.isEnabled
- }
+ val callback = inProgressCallback ?: onBackPressedCallbacks.lastOrNull { it.isEnabled }
inProgressCallback = null
if (callback != null) {
callback.handleOnBackCancelled()
@@ -325,10 +305,7 @@
lifecycle.addObserver(this)
}
- override fun onStateChanged(
- source: LifecycleOwner,
- event: Lifecycle.Event
- ) {
+ override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (event === Lifecycle.Event.ON_START) {
currentCancellable = addCancellableCallback(onBackPressedCallback)
} else if (event === Lifecycle.Event.ON_STOP) {
@@ -350,11 +327,7 @@
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
internal object Api33Impl {
@DoNotInline
- fun registerOnBackInvokedCallback(
- dispatcher: Any,
- priority: Int,
- callback: Any
- ) {
+ fun registerOnBackInvokedCallback(dispatcher: Any, priority: Int, callback: Any) {
val onBackInvokedDispatcher = dispatcher as OnBackInvokedDispatcher
val onBackInvokedCallback = callback as OnBackInvokedCallback
onBackInvokedDispatcher.registerOnBackInvokedCallback(priority, onBackInvokedCallback)
@@ -418,11 +391,12 @@
enabled: Boolean = true,
onBackPressed: OnBackPressedCallback.() -> Unit
): OnBackPressedCallback {
- val callback = object : OnBackPressedCallback(enabled) {
- override fun handleOnBackPressed() {
- onBackPressed()
+ val callback =
+ object : OnBackPressedCallback(enabled) {
+ override fun handleOnBackPressed() {
+ onBackPressed()
+ }
}
- }
if (owner != null) {
addCallback(owner, callback)
} else {
diff --git a/activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcherOwner.kt b/activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcherOwner.kt
index 7feb42e..6e9bae8 100644
--- a/activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcherOwner.kt
+++ b/activity/activity/src/main/java/androidx/activity/OnBackPressedDispatcherOwner.kt
@@ -21,14 +21,12 @@
* A class that has an [OnBackPressedDispatcher] that allows you to register a
* [OnBackPressedCallback] for handling the system back button.
*
- * It is expected that classes that implement this interface route the system back button
- * to the dispatcher
+ * It is expected that classes that implement this interface route the system back button to the
+ * dispatcher
*
* @see OnBackPressedDispatcher
*/
interface OnBackPressedDispatcherOwner : LifecycleOwner {
- /**
- * The [OnBackPressedDispatcher] that should handle the system back button.
- */
+ /** The [OnBackPressedDispatcher] that should handle the system back button. */
val onBackPressedDispatcher: OnBackPressedDispatcher
}
diff --git a/activity/activity/src/main/java/androidx/activity/PipHintTracker.kt b/activity/activity/src/main/java/androidx/activity/PipHintTracker.kt
index d130d7f..4171638 100644
--- a/activity/activity/src/main/java/androidx/activity/PipHintTracker.kt
+++ b/activity/activity/src/main/java/androidx/activity/PipHintTracker.kt
@@ -30,8 +30,8 @@
* Sets the [View] that will be used as reference to set the
* [PictureInPictureParams.Builder.setSourceRectHint].
*
- * Anytime the view position changes, [Activity.setPictureInPictureParams] will be called with
- * the updated view's position in window coordinates as the
+ * Anytime the view position changes, [Activity.setPictureInPictureParams] will be called with the
+ * updated view's position in window coordinates as the
* [PictureInPictureParams.Builder.setSourceRectHint].
*
* @param view the view to use as the reference for the source rect hint
@@ -48,58 +48,55 @@
// Create a cold flow that will emit the most updated position of the view in the form of a
// rect as long as the view is attached to the window.
@Suppress("DEPRECATION")
- val flow = callbackFlow<Rect> {
- // Emit a new hint rect any time the view moves.
- val layoutChangeListener = View.OnLayoutChangeListener { v, l, t, r, b, oldLeft, oldTop,
- oldRight, oldBottom ->
- if (l != oldLeft || r != oldRight || t != oldTop || b != oldBottom) {
- trySend(v.positionInWindow())
- }
- }
- val scrollChangeListener = ViewTreeObserver.OnScrollChangedListener {
- trySend(view.positionInWindow())
- }
- // When the view is attached, emit the current position and start listening for layout
- // changes to track movement.
- val attachStateChangeListener = object : View.OnAttachStateChangeListener {
- override fun onViewAttachedToWindow(v: View) {
+ val flow =
+ callbackFlow<Rect> {
+ // Emit a new hint rect any time the view moves.
+ val layoutChangeListener =
+ View.OnLayoutChangeListener { v, l, t, r, b, oldLeft, oldTop, oldRight, oldBottom ->
+ if (l != oldLeft || r != oldRight || t != oldTop || b != oldBottom) {
+ trySend(v.positionInWindow())
+ }
+ }
+ val scrollChangeListener =
+ ViewTreeObserver.OnScrollChangedListener { trySend(view.positionInWindow()) }
+ // When the view is attached, emit the current position and start listening for layout
+ // changes to track movement.
+ val attachStateChangeListener =
+ object : View.OnAttachStateChangeListener {
+ override fun onViewAttachedToWindow(v: View) {
+ trySend(view.positionInWindow())
+ view.viewTreeObserver.addOnScrollChangedListener(scrollChangeListener)
+ view.addOnLayoutChangeListener(layoutChangeListener)
+ }
+
+ override fun onViewDetachedFromWindow(v: View) {
+ v.viewTreeObserver.removeOnScrollChangedListener(scrollChangeListener)
+ v.removeOnLayoutChangeListener(layoutChangeListener)
+ }
+ }
+ // Check if the view is already attached to the window, if it is then emit the current
+ // position and start listening for layout changes to track movement.
+ if (view.isAttachedToWindow) {
trySend(view.positionInWindow())
view.viewTreeObserver.addOnScrollChangedListener(scrollChangeListener)
view.addOnLayoutChangeListener(layoutChangeListener)
}
+ view.addOnAttachStateChangeListener(attachStateChangeListener)
- override fun onViewDetachedFromWindow(v: View) {
- v.viewTreeObserver.removeOnScrollChangedListener(scrollChangeListener)
- v.removeOnLayoutChangeListener(layoutChangeListener)
+ awaitClose {
+ view.viewTreeObserver.removeOnScrollChangedListener(scrollChangeListener)
+ view.removeOnLayoutChangeListener(layoutChangeListener)
+ view.removeOnAttachStateChangeListener(attachStateChangeListener)
}
}
- // Check if the view is already attached to the window, if it is then emit the current
- // position and start listening for layout changes to track movement.
- if (view.isAttachedToWindow) {
- trySend(view.positionInWindow())
- view.viewTreeObserver.addOnScrollChangedListener(scrollChangeListener)
- view.addOnLayoutChangeListener(layoutChangeListener)
- }
- view.addOnAttachStateChangeListener(attachStateChangeListener)
-
- awaitClose {
- view.viewTreeObserver.removeOnScrollChangedListener(scrollChangeListener)
- view.removeOnLayoutChangeListener(layoutChangeListener)
- view.removeOnAttachStateChangeListener(attachStateChangeListener)
- }
- }
- flow.collect { hint ->
- Api26Impl.setPipParamsSourceRectHint(this, hint)
- }
+ flow.collect { hint -> Api26Impl.setPipParamsSourceRectHint(this, hint) }
}
@RequiresApi(Build.VERSION_CODES.O)
internal object Api26Impl {
fun setPipParamsSourceRectHint(activity: Activity, hint: Rect) {
activity.setPictureInPictureParams(
- PictureInPictureParams.Builder()
- .setSourceRectHint(hint)
- .build()
+ PictureInPictureParams.Builder().setSourceRectHint(hint).build()
)
}
}
diff --git a/activity/activity/src/main/java/androidx/activity/ViewTreeFullyLoadedReporterOwner.kt b/activity/activity/src/main/java/androidx/activity/ViewTreeFullyLoadedReporterOwner.kt
index 4128135..3f7692df 100644
--- a/activity/activity/src/main/java/androidx/activity/ViewTreeFullyLoadedReporterOwner.kt
+++ b/activity/activity/src/main/java/androidx/activity/ViewTreeFullyLoadedReporterOwner.kt
@@ -20,35 +20,30 @@
import android.view.View
/**
- * Set the [FullyDrawnReporterOwner] associated with the given [View].
- * Calls to [findViewTreeFullyDrawnReporterOwner] from this [View] or descendants will
- * return [fullyDrawnReporterOwner].
+ * Set the [FullyDrawnReporterOwner] associated with the given [View]. Calls to
+ * [findViewTreeFullyDrawnReporterOwner] from this [View] or descendants will return
+ * [fullyDrawnReporterOwner].
*
- * This should only be called by constructs such as activities that manage
- * a view tree and handle the dispatch of [ComponentActivity.reportFullyDrawn].
+ * This should only be called by constructs such as activities that manage a view tree and handle
+ * the dispatch of [ComponentActivity.reportFullyDrawn].
*
* @param fullyDrawnReporterOwner [FullyDrawnReporterOwner] associated with the [View]
*/
@JvmName("set")
-fun View.setViewTreeFullyDrawnReporterOwner(
- fullyDrawnReporterOwner: FullyDrawnReporterOwner
-) {
+fun View.setViewTreeFullyDrawnReporterOwner(fullyDrawnReporterOwner: FullyDrawnReporterOwner) {
setTag(R.id.report_drawn, fullyDrawnReporterOwner)
}
/**
- * Retrieve the [FullyDrawnReporterOwner] associated with the given [View].
- * This may be used to indicate that a part of the UI is drawn and ready for first
- * user interaction.
+ * Retrieve the [FullyDrawnReporterOwner] associated with the given [View]. This may be used to
+ * indicate that a part of the UI is drawn and ready for first user interaction.
*
- * @return The [FullyDrawnReporterOwner] associated with this view and/or some subset
- * of its ancestors
+ * @return The [FullyDrawnReporterOwner] associated with this view and/or some subset of its
+ * ancestors
*/
@JvmName("get")
fun View.findViewTreeFullyDrawnReporterOwner(): FullyDrawnReporterOwner? {
- return generateSequence(this) {
- it.parent as? View
- }.mapNotNull {
- it.getTag(R.id.report_drawn) as? FullyDrawnReporterOwner
- }.firstOrNull()
+ return generateSequence(this) { it.parent as? View }
+ .mapNotNull { it.getTag(R.id.report_drawn) as? FullyDrawnReporterOwner }
+ .firstOrNull()
}
diff --git a/activity/activity/src/main/java/androidx/activity/ViewTreeOnBackPressedDispatcherOwner.kt b/activity/activity/src/main/java/androidx/activity/ViewTreeOnBackPressedDispatcherOwner.kt
index 620efda..06f80e3 100644
--- a/activity/activity/src/main/java/androidx/activity/ViewTreeOnBackPressedDispatcherOwner.kt
+++ b/activity/activity/src/main/java/androidx/activity/ViewTreeOnBackPressedDispatcherOwner.kt
@@ -21,13 +21,13 @@
import android.view.View
/**
- * Set the [OnBackPressedDispatcherOwner] associated with the given [View].
- * Calls to [findViewTreeOnBackPressedDispatcherOwner] from this view or descendants will
- * return [onBackPressedDispatcherOwner].
+ * Set the [OnBackPressedDispatcherOwner] associated with the given [View]. Calls to
+ * [findViewTreeOnBackPressedDispatcherOwner] from this view or descendants will return
+ * [onBackPressedDispatcherOwner].
*
- * This should only be called by constructs such as activities or dialogs that manage
- * a view tree and handle the dispatch of the system back button. Callers
- * should only set a [OnBackPressedDispatcherOwner] that will be *stable.*
+ * This should only be called by constructs such as activities or dialogs that manage a view tree
+ * and handle the dispatch of the system back button. Callers should only set a
+ * [OnBackPressedDispatcherOwner] that will be *stable.*
*
* @param onBackPressedDispatcherOwner [OnBackPressedDispatcherOwner] associated with the [View]
*/
@@ -39,17 +39,18 @@
}
/**
- * Retrieve the [OnBackPressedDispatcherOwner] associated with the given [View].
- * This may be used to add a callback for the system back button.
+ * Retrieve the [OnBackPressedDispatcherOwner] associated with the given [View]. This may be used to
+ * add a callback for the system back button.
*
- * @return The [OnBackPressedDispatcherOwner] associated with this view and/or some subset
- * of its ancestors
+ * @return The [OnBackPressedDispatcherOwner] associated with this view and/or some subset of its
+ * ancestors
*/
@JvmName("get")
fun View.findViewTreeOnBackPressedDispatcherOwner(): OnBackPressedDispatcherOwner? {
- return generateSequence(this) {
- it.parent as? View
- }.mapNotNull {
- it.getTag(R.id.view_tree_on_back_pressed_dispatcher_owner) as? OnBackPressedDispatcherOwner
- }.firstOrNull()
+ return generateSequence(this) { it.parent as? View }
+ .mapNotNull {
+ it.getTag(R.id.view_tree_on_back_pressed_dispatcher_owner)
+ as? OnBackPressedDispatcherOwner
+ }
+ .firstOrNull()
}
diff --git a/activity/activity/src/main/java/androidx/activity/contextaware/ContextAware.kt b/activity/activity/src/main/java/androidx/activity/contextaware/ContextAware.kt
index 866856d..c74cde3 100644
--- a/activity/activity/src/main/java/androidx/activity/contextaware/ContextAware.kt
+++ b/activity/activity/src/main/java/androidx/activity/contextaware/ContextAware.kt
@@ -19,29 +19,27 @@
import kotlinx.coroutines.suspendCancellableCoroutine
/**
- * A `ContextAware` class is associated with a [Context] sometime after
- * the class is instantiated. By adding a [OnContextAvailableListener], you can
- * receive a callback for that event.
+ * A `ContextAware` class is associated with a [Context] sometime after the class is instantiated.
+ * By adding a [OnContextAvailableListener], you can receive a callback for that event.
*
* Classes implementing [ContextAware] are strongly recommended to also implement
- * [androidx.lifecycle.LifecycleOwner] for providing a more general purpose API for
- * listening for creation and destruction events.
+ * [androidx.lifecycle.LifecycleOwner] for providing a more general purpose API for listening for
+ * creation and destruction events.
*
* @see ContextAwareHelper
*/
interface ContextAware {
/**
- * Get the [Context] if it is currently available. If this returns
- * `null`, you can use [addOnContextAvailableListener] to receive
- * a callback for when it available.
+ * Get the [Context] if it is currently available. If this returns `null`, you can use
+ * [addOnContextAvailableListener] to receive a callback for when it available.
*
* @return the Context if it is currently available.
*/
fun peekAvailableContext(): Context?
/**
- * Add a new [OnContextAvailableListener] for receiving a callback for when
- * this class is associated with a [android.content.Context].
+ * Add a new [OnContextAvailableListener] for receiving a callback for when this class is
+ * associated with a [android.content.Context].
*
* Listeners are triggered in the order they are added when added before the Context is
* available. Listeners added after the context has been made available will have the Context
@@ -53,8 +51,7 @@
fun addOnContextAvailableListener(listener: OnContextAvailableListener)
/**
- * Remove a [OnContextAvailableListener] previously added via
- * [addOnContextAvailableListener].
+ * Remove a [OnContextAvailableListener] previously added via [addOnContextAvailableListener].
*
* @param listener The listener that should be removed.
* @see addOnContextAvailableListener
@@ -63,13 +60,11 @@
}
/**
- * Run [onContextAvailable] when the [Context] becomes available and
- * resume with the result.
+ * Run [onContextAvailable] when the [Context] becomes available and resume with the result.
*
- * If the [Context] is already available, [onContextAvailable] will be
- * synchronously called on the current coroutine context. Otherwise,
- * [onContextAvailable] will be called on the UI thread immediately when
- * the Context becomes available.
+ * If the [Context] is already available, [onContextAvailable] will be synchronously called on the
+ * current coroutine context. Otherwise, [onContextAvailable] will be called on the UI thread
+ * immediately when the Context becomes available.
*/
suspend inline fun <R> ContextAware.withContextAvailable(
crossinline onContextAvailable: (@JvmSuppressWildcards Context) -> @JvmSuppressWildcards R
@@ -79,15 +74,14 @@
onContextAvailable(availableContext)
} else {
suspendCancellableCoroutine { co ->
- val listener = object : OnContextAvailableListener {
- override fun onContextAvailable(context: Context) {
- co.resumeWith(runCatching { onContextAvailable(context) })
+ val listener =
+ object : OnContextAvailableListener {
+ override fun onContextAvailable(context: Context) {
+ co.resumeWith(runCatching { onContextAvailable(context) })
+ }
}
- }
addOnContextAvailableListener(listener)
- co.invokeOnCancellation {
- removeOnContextAvailableListener(listener)
- }
+ co.invokeOnCancellation { removeOnContextAvailableListener(listener) }
}
}
}
diff --git a/activity/activity/src/main/java/androidx/activity/contextaware/ContextAwareHelper.kt b/activity/activity/src/main/java/androidx/activity/contextaware/ContextAwareHelper.kt
index 7ef4f5c..4bef4aa 100644
--- a/activity/activity/src/main/java/androidx/activity/contextaware/ContextAwareHelper.kt
+++ b/activity/activity/src/main/java/androidx/activity/contextaware/ContextAwareHelper.kt
@@ -19,27 +19,24 @@
import java.util.concurrent.CopyOnWriteArraySet
/**
- * Helper class for implementing [ContextAware]. Classes using this helper should
- * call [addOnContextAvailableListener] and [removeOnContextAvailableListener] as the respective
- * methods of [ContextAware] are called.
+ * Helper class for implementing [ContextAware]. Classes using this helper should call
+ * [addOnContextAvailableListener] and [removeOnContextAvailableListener] as the respective methods
+ * of [ContextAware] are called.
*
- * You must call [dispatchOnContextAvailable] once the
- * [Context] is available to dispatch the callbacks to all registered listeners.
+ * You must call [dispatchOnContextAvailable] once the [Context] is available to dispatch the
+ * callbacks to all registered listeners.
*
- * Listeners added after the context has been made available via
- * [dispatchOnContextAvailable] will have the Context synchronously
- * delivered to them up until [clearAvailableContext] is called.
+ * Listeners added after the context has been made available via [dispatchOnContextAvailable] will
+ * have the Context synchronously delivered to them up until [clearAvailableContext] is called.
*/
class ContextAwareHelper {
private val listeners: MutableSet<OnContextAvailableListener> = CopyOnWriteArraySet()
- @Volatile
- private var context: Context? = null
+ @Volatile private var context: Context? = null
/**
- * Get the [Context] if it is currently available. If this returns
- * `null`, you can use [addOnContextAvailableListener] to receive
- * a callback for when it available.
+ * Get the [Context] if it is currently available. If this returns `null`, you can use
+ * [addOnContextAvailableListener] to receive a callback for when it available.
*
* @return the Context if it is currently available.
*/
@@ -48,22 +45,19 @@
}
/**
- * Add a new [OnContextAvailableListener] for receiving a callback for when
- * this class is associated with a [android.content.Context].
+ * Add a new [OnContextAvailableListener] for receiving a callback for when this class is
+ * associated with a [android.content.Context].
*
* @param listener The listener that should be added.
* @see removeOnContextAvailableListener
*/
fun addOnContextAvailableListener(listener: OnContextAvailableListener) {
- context?.let {
- listener.onContextAvailable(it)
- }
+ context?.let { listener.onContextAvailable(it) }
listeners.add(listener)
}
/**
- * Remove a [OnContextAvailableListener] previously added via
- * [addOnContextAvailableListener].
+ * Remove a [OnContextAvailableListener] previously added via [addOnContextAvailableListener].
*
* @param listener The listener that should be removed.
* @see addOnContextAvailableListener
@@ -73,8 +67,8 @@
}
/**
- * Dispatch the callback of [OnContextAvailableListener.onContextAvailable] to
- * all currently added listeners in the order they were added.
+ * Dispatch the callback of [OnContextAvailableListener.onContextAvailable] to all currently
+ * added listeners in the order they were added.
*
* @param context The [Context] the [ContextAware] object is now associated with.
*/
@@ -85,10 +79,7 @@
}
}
- /**
- * Clear any [Context] previously made available via
- * [dispatchOnContextAvailable].
- */
+ /** Clear any [Context] previously made available via [dispatchOnContextAvailable]. */
fun clearAvailableContext() {
context = null
}
diff --git a/activity/activity/src/main/java/androidx/activity/contextaware/OnContextAvailableListener.kt b/activity/activity/src/main/java/androidx/activity/contextaware/OnContextAvailableListener.kt
index 726b2bb..e8124766 100644
--- a/activity/activity/src/main/java/androidx/activity/contextaware/OnContextAvailableListener.kt
+++ b/activity/activity/src/main/java/androidx/activity/contextaware/OnContextAvailableListener.kt
@@ -18,8 +18,8 @@
import android.content.Context
/**
- * Listener for receiving a callback at the first moment a [Context] is made
- * available to the [ContextAware] class.
+ * Listener for receiving a callback at the first moment a [Context] is made available to the
+ * [ContextAware] class.
*
* @see ContextAware.addOnContextAvailableListener
*/
diff --git a/activity/activity/src/main/java/androidx/activity/result/ActivityResult.kt b/activity/activity/src/main/java/androidx/activity/result/ActivityResult.kt
index bbd1a03..1e29886 100644
--- a/activity/activity/src/main/java/androidx/activity/result/ActivityResult.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/ActivityResult.kt
@@ -28,18 +28,16 @@
*/
@SuppressLint("BanParcelableUsage")
class ActivityResult(
- /**
- * Status to indicate the success of the operation
- */
+ /** Status to indicate the success of the operation */
val resultCode: Int,
- /**
- * The intent that carries the result data
- */
+ /** The intent that carries the result data */
val data: Intent?
) : Parcelable {
- internal constructor(parcel: Parcel) : this(
+ internal constructor(
+ parcel: Parcel
+ ) : this(
parcel.readInt(),
if (parcel.readInt() == 0) null else Intent.CREATOR.createFromParcel(parcel)
)
@@ -73,11 +71,12 @@
@Suppress("unused")
@JvmField
- val CREATOR = object : Parcelable.Creator<ActivityResult> {
- override fun createFromParcel(parcel: Parcel) = ActivityResult(parcel)
+ val CREATOR =
+ object : Parcelable.Creator<ActivityResult> {
+ override fun createFromParcel(parcel: Parcel) = ActivityResult(parcel)
- override fun newArray(size: Int) = arrayOfNulls<ActivityResult>(size)
- }
+ override fun newArray(size: Int) = arrayOfNulls<ActivityResult>(size)
+ }
}
}
diff --git a/activity/activity/src/main/java/androidx/activity/result/ActivityResultCallback.kt b/activity/activity/src/main/java/androidx/activity/result/ActivityResultCallback.kt
index 1c500f4..21170ec 100644
--- a/activity/activity/src/main/java/androidx/activity/result/ActivityResultCallback.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/ActivityResultCallback.kt
@@ -18,12 +18,10 @@
import android.app.Activity
/**
- * A type-safe callback to be called when an [activity result][Activity.onActivityResult]
- * is available.
+ * A type-safe callback to be called when an [activity result][Activity.onActivityResult] is
+ * available.
*/
fun interface ActivityResultCallback<O> {
- /**
- * Called when result is available
- */
+ /** Called when result is available */
fun onActivityResult(result: O)
}
diff --git a/activity/activity/src/main/java/androidx/activity/result/ActivityResultCaller.kt b/activity/activity/src/main/java/androidx/activity/result/ActivityResultCaller.kt
index afd7e34..03387f9 100644
--- a/activity/activity/src/main/java/androidx/activity/result/ActivityResultCaller.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/ActivityResultCaller.kt
@@ -30,19 +30,17 @@
* Register a request to [start an activity for result][Activity.startActivityForResult],
* designated by the given [contract][ActivityResultContract].
*
- * This creates a record in the [registry][ActivityResultRegistry] associated with this
- * caller, managing request code, as well as conversions to/from [Intent] under the hood.
+ * This creates a record in the [registry][ActivityResultRegistry] associated with this caller,
+ * managing request code, as well as conversions to/from [Intent] under the hood.
*
* This *must* be called unconditionally, as part of initialization path, typically as a field
* initializer of an Activity or Fragment.
*
* @param I the type of the input(if any) required to call the activity
* @param O the type of output returned as an activity result
- *
* @param contract the contract, specifying conversions to/from [Intent]s
- * @param callback the callback to be called on the main thread when activity result
- * is available
- *
+ * @param callback the callback to be called on the main thread when activity result is
+ * available
* @return the launcher that can be used to start the activity or dispose of the prepared call.
*/
fun <I, O> registerForActivityResult(
@@ -54,20 +52,18 @@
* Register a request to [start an activity for result][Activity.startActivityForResult],
* designated by the given [contract][ActivityResultContract].
*
- * This creates a record in the given [registry][ActivityResultRegistry], managing request
- * code, as well as conversions to/from [Intent] under the hood.
+ * This creates a record in the given [registry][ActivityResultRegistry], managing request code,
+ * as well as conversions to/from [Intent] under the hood.
*
* This *must* be called unconditionally, as part of initialization path, typically as a field
* initializer of an Activity or Fragment.
*
* @param I the type of the input(if any) required to call the activity
* @param O the type of output returned as an activity result
- *
* @param contract the contract, specifying conversions to/from [Intent]s
* @param registry the registry where to hold the record.
- * @param callback the callback to be called on the main thread when activity result
- * is available
- *
+ * @param callback the callback to be called on the main thread when activity result is
+ * available
* @return the launcher that can be used to start the activity or dispose of the prepared call.
*/
fun <I, O> registerForActivityResult(
@@ -78,9 +74,8 @@
}
/**
- * A version of [ActivityResultCaller.registerForActivityResult]
- * that additionally takes an input right away, producing a launcher that doesn't take any
- * additional input when called.
+ * A version of [ActivityResultCaller.registerForActivityResult] that additionally takes an input
+ * right away, producing a launcher that doesn't take any additional input when called.
*
* @see ActivityResultCaller.registerForActivityResult
*/
@@ -95,9 +90,8 @@
}
/**
- * A version of [ActivityResultCaller.registerForActivityResult]
- * that additionally takes an input right away, producing a launcher that doesn't take any
- * additional input when called.
+ * A version of [ActivityResultCaller.registerForActivityResult] that additionally takes an input
+ * right away, producing a launcher that doesn't take any additional input when called.
*
* @see ActivityResultCaller.registerForActivityResult
*/
diff --git a/activity/activity/src/main/java/androidx/activity/result/ActivityResultLauncher.kt b/activity/activity/src/main/java/androidx/activity/result/ActivityResultLauncher.kt
index 6986b48..d520f3f 100644
--- a/activity/activity/src/main/java/androidx/activity/result/ActivityResultLauncher.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/ActivityResultLauncher.kt
@@ -20,16 +20,16 @@
import androidx.core.app.ActivityOptionsCompat
/**
- * A launcher for a previously-[prepared call][ActivityResultCaller.registerForActivityResult]
- * to start the process of executing an [ActivityResultContract] that takes an [I] as its required
+ * A launcher for a previously-[prepared call][ActivityResultCaller.registerForActivityResult] to
+ * start the process of executing an [ActivityResultContract] that takes an [I] as its required
* input.
*/
abstract class ActivityResultLauncher<I> {
/**
* Executes an [ActivityResultContract] given the required [input].
*
- * This method throws [android.content.ActivityNotFoundException]
- * if there was no Activity found to run the given Intent.
+ * This method throws [android.content.ActivityNotFoundException] if there was no Activity found
+ * to run the given Intent.
*
* @throws android.content.ActivityNotFoundException
*/
@@ -38,11 +38,11 @@
}
/**
- * Executes an [ActivityResultContract] given the required [input] and optional
- * [options] for how the Activity should be started.
+ * Executes an [ActivityResultContract] given the required [input] and optional [options] for
+ * how the Activity should be started.
*
- * This method throws [android.content.ActivityNotFoundException]
- * if there was no Activity found to run the given Intent.
+ * This method throws [android.content.ActivityNotFoundException] if there was no Activity found
+ * to run the given Intent.
*
* @throws android.content.ActivityNotFoundException
*/
@@ -55,25 +55,18 @@
* You should call this if the registry may live longer than the callback registered for this
* launcher.
*/
- @MainThread
- abstract fun unregister()
+ @MainThread abstract fun unregister()
- /**
- * Returns the [ActivityResultContract] that was used to create this launcher.
- */
+ /** Returns the [ActivityResultContract] that was used to create this launcher. */
abstract val contract: ActivityResultContract<I, *>
}
-/**
- * Convenience method to launch a no-argument registered call without needing to pass in `null`.
- */
+/** Convenience method to launch a no-argument registered call without needing to pass in `null`. */
fun ActivityResultLauncher<Void?>.launch(options: ActivityOptionsCompat? = null) {
launch(null, options)
}
-/**
- * Convenience method to launch a no-argument registered call without needing to pass in `Unit`.
- */
+/** Convenience method to launch a no-argument registered call without needing to pass in `Unit`. */
@JvmName("launchUnit")
fun ActivityResultLauncher<Unit>.launch(options: ActivityOptionsCompat? = null) {
launch(Unit, options)
diff --git a/activity/activity/src/main/java/androidx/activity/result/ActivityResultRegistry.kt b/activity/activity/src/main/java/androidx/activity/result/ActivityResultRegistry.kt
index 4d73896..40997d2 100644
--- a/activity/activity/src/main/java/androidx/activity/result/ActivityResultRegistry.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/ActivityResultRegistry.kt
@@ -44,18 +44,14 @@
private val keyToRc = mutableMapOf<String, Int>()
private val keyToLifecycleContainers = mutableMapOf<String, LifecycleContainer>()
private val launchedKeys = mutableListOf<String>()
- @Transient
- private val keyToCallback = mutableMapOf<String, CallbackAndContract<*>>()
+ @Transient private val keyToCallback = mutableMapOf<String, CallbackAndContract<*>>()
private val parsedPendingResults = mutableMapOf<String, Any?>()
- /**
- * Storage for the set of key to ActivityResult instances that have
- * yet to be delivered
- */
+ /** Storage for the set of key to ActivityResult instances that have yet to be delivered */
private val pendingResults = Bundle()
/**
- * Start the process of executing an [ActivityResultContract] in a type-safe way,
- * using the provided [contract][ActivityResultContract].
+ * Start the process of executing an [ActivityResultContract] in a type-safe way, using the
+ * provided [contract][ActivityResultContract].
*
* @param requestCode request code to use
* @param contract contract to use for type conversions
@@ -80,7 +76,6 @@
* @param lifecycleOwner a [LifecycleOwner] that makes this call.
* @param contract the contract specifying input/output types of the call
* @param callback the activity result callback
- *
* @return a launcher that can be used to execute an ActivityResultContract.
*/
fun <I, O> register(
@@ -106,15 +101,12 @@
parsedPendingResults.remove(key)
callback.onActivityResult(parsedPendingResult)
}
- val pendingResult = BundleCompat.getParcelable(pendingResults, key,
- ActivityResult::class.java)
+ val pendingResult =
+ BundleCompat.getParcelable(pendingResults, key, ActivityResult::class.java)
if (pendingResult != null) {
pendingResults.remove(key)
callback.onActivityResult(
- contract.parseResult(
- pendingResult.resultCode,
- pendingResult.data
- )
+ contract.parseResult(pendingResult.resultCode, pendingResult.data)
)
}
} else if (Lifecycle.Event.ON_STOP == event) {
@@ -127,11 +119,12 @@
keyToLifecycleContainers[key] = lifecycleContainer
return object : ActivityResultLauncher<I>() {
override fun launch(input: I, options: ActivityOptionsCompat?) {
- val innerCode = checkNotNull(keyToRc[key]) {
- "Attempting to launch an unregistered ActivityResultLauncher with " +
- "contract $contract and input $input. You must ensure the " +
- "ActivityResultLauncher is registered before calling launch()."
- }
+ val innerCode =
+ checkNotNull(keyToRc[key]) {
+ "Attempting to launch an unregistered ActivityResultLauncher with " +
+ "contract $contract and input $input. You must ensure the " +
+ "ActivityResultLauncher is registered before calling launch()."
+ }
launchedKeys.add(key)
try {
onLaunch(innerCode, contract, input, options)
@@ -156,14 +149,13 @@
* This is normally called by a higher level convenience methods like
* [ActivityResultCaller.registerForActivityResult].
*
- * When calling this, you must call [ActivityResultLauncher.unregister] on the
- * returned [ActivityResultLauncher] when the launcher is no longer needed to
- * release any values that might be captured in the registered callback.
+ * When calling this, you must call [ActivityResultLauncher.unregister] on the returned
+ * [ActivityResultLauncher] when the launcher is no longer needed to release any values that
+ * might be captured in the registered callback.
*
* @param key a unique string key identifying this call
* @param contract the contract specifying input/output types of the call
* @param callback the activity result callback
- *
* @return a launcher that can be used to execute an ActivityResultContract.
*/
fun <I, O> register(
@@ -174,13 +166,12 @@
registerKey(key)
keyToCallback[key] = CallbackAndContract(callback, contract)
if (parsedPendingResults.containsKey(key)) {
- @Suppress("UNCHECKED_CAST")
- val parsedPendingResult = parsedPendingResults[key] as O
+ @Suppress("UNCHECKED_CAST") val parsedPendingResult = parsedPendingResults[key] as O
parsedPendingResults.remove(key)
callback.onActivityResult(parsedPendingResult)
}
- val pendingResult = BundleCompat.getParcelable(pendingResults, key,
- ActivityResult::class.java)
+ val pendingResult =
+ BundleCompat.getParcelable(pendingResults, key, ActivityResult::class.java)
if (pendingResult != null) {
pendingResults.remove(key)
callback.onActivityResult(
@@ -189,11 +180,12 @@
}
return object : ActivityResultLauncher<I>() {
override fun launch(input: I, options: ActivityOptionsCompat?) {
- val innerCode = checkNotNull(keyToRc[key]) {
- "Attempting to launch an unregistered ActivityResultLauncher with " +
- "contract $contract and input $input. You must ensure the " +
- "ActivityResultLauncher is registered before calling launch()."
- }
+ val innerCode =
+ checkNotNull(keyToRc[key]) {
+ "Attempting to launch an unregistered ActivityResultLauncher with " +
+ "contract $contract and input $input. You must ensure the " +
+ "ActivityResultLauncher is registered before calling launch()."
+ }
launchedKeys.add(key)
try {
onLaunch(innerCode, contract, input, options)
@@ -213,8 +205,8 @@
}
/**
- * Unregister a callback previously registered with [register]. This shouldn't be
- * called directly, but instead through [ActivityResultLauncher.unregister].
+ * Unregister a callback previously registered with [register]. This shouldn't be called
+ * directly, but instead through [ActivityResultLauncher.unregister].
*
* @param key the unique key used when registering a callback.
*/
@@ -229,15 +221,13 @@
}
keyToCallback.remove(key)
if (parsedPendingResults.containsKey(key)) {
- Log.w(LOG_TAG,
- "Dropping pending result for request $key: ${parsedPendingResults[key]}")
+ Log.w(LOG_TAG, "Dropping pending result for request $key: ${parsedPendingResults[key]}")
parsedPendingResults.remove(key)
}
if (pendingResults.containsKey(key)) {
- val pendingResult = BundleCompat.getParcelable(pendingResults, key,
- ActivityResult::class.java)
- Log.w(LOG_TAG,
- "Dropping pending result for request $key: $pendingResult")
+ val pendingResult =
+ BundleCompat.getParcelable(pendingResults, key, ActivityResult::class.java)
+ Log.w(LOG_TAG, "Dropping pending result for request $key: $pendingResult")
pendingResults.remove(key)
}
val lifecycleContainer = keyToLifecycleContainers[key]
@@ -257,18 +247,9 @@
KEY_COMPONENT_ACTIVITY_REGISTERED_RCS,
ArrayList(keyToRc.values)
)
- outState.putStringArrayList(
- KEY_COMPONENT_ACTIVITY_REGISTERED_KEYS,
- ArrayList(keyToRc.keys)
- )
- outState.putStringArrayList(
- KEY_COMPONENT_ACTIVITY_LAUNCHED_KEYS,
- ArrayList(launchedKeys)
- )
- outState.putBundle(
- KEY_COMPONENT_ACTIVITY_PENDING_RESULTS,
- Bundle(pendingResults)
- )
+ outState.putStringArrayList(KEY_COMPONENT_ACTIVITY_REGISTERED_KEYS, ArrayList(keyToRc.keys))
+ outState.putStringArrayList(KEY_COMPONENT_ACTIVITY_LAUNCHED_KEYS, ArrayList(launchedKeys))
+ outState.putBundle(KEY_COMPONENT_ACTIVITY_PENDING_RESULTS, Bundle(pendingResults))
}
/**
@@ -285,13 +266,13 @@
if (keys == null || rcs == null) {
return
}
- val restoredLaunchedKeys = savedInstanceState.getStringArrayList(
- KEY_COMPONENT_ACTIVITY_LAUNCHED_KEYS)
+ val restoredLaunchedKeys =
+ savedInstanceState.getStringArrayList(KEY_COMPONENT_ACTIVITY_LAUNCHED_KEYS)
if (restoredLaunchedKeys != null) {
launchedKeys.addAll(restoredLaunchedKeys)
}
- val restoredPendingResults = savedInstanceState.getBundle(
- KEY_COMPONENT_ACTIVITY_PENDING_RESULTS)
+ val restoredPendingResults =
+ savedInstanceState.getBundle(KEY_COMPONENT_ACTIVITY_PENDING_RESULTS)
if (restoredPendingResults != null) {
pendingResults.putAll(restoredPendingResults)
}
@@ -315,15 +296,14 @@
}
/**
- * Dispatch a result received via [Activity.onActivityResult] to the callback on record,
- * or store the result if callback was not yet registered.
+ * Dispatch a result received via [Activity.onActivityResult] to the callback on record, or
+ * store the result if callback was not yet registered.
*
* @param requestCode request code to identify the callback
* @param resultCode status to indicate the success of the operation
* @param data an intent that carries the result data
- *
- * @return whether there was a callback was registered for the given request code which was
- * or will be called.
+ * @return whether there was a callback was registered for the given request code which was or
+ * will be called.
*/
@MainThread
fun dispatchResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
@@ -337,7 +317,6 @@
*
* @param requestCode request code to identify the callback
* @param result the result to propagate
- *
* @return true if there is a callback registered for the given request code, false otherwise.
*/
@MainThread
@@ -388,19 +367,17 @@
}
/**
- * Generate a random number between the initial value (00010000) inclusive, and the max
- * integer value. If that number is already an existing request code, generate another until
- * we find one that is new.
+ * Generate a random number between the initial value (00010000) inclusive, and the max integer
+ * value. If that number is already an existing request code, generate another until we find one
+ * that is new.
*
* @return the number
*/
private fun generateRandomNumber(): Int {
return generateSequence {
- nextInt(Int.MAX_VALUE - INITIAL_REQUEST_CODE_VALUE + 1) +
- INITIAL_REQUEST_CODE_VALUE
- }.first { number ->
- !rcToKey.containsKey(number)
- }
+ nextInt(Int.MAX_VALUE - INITIAL_REQUEST_CODE_VALUE + 1) + INITIAL_REQUEST_CODE_VALUE
+ }
+ .first { number -> !rcToKey.containsKey(number) }
}
private fun bindRcKey(rc: Int, key: String) {
@@ -422,9 +399,7 @@
}
fun clearObservers() {
- observers.forEach { observer ->
- lifecycle.removeObserver(observer)
- }
+ observers.forEach { observer -> lifecycle.removeObserver(observer) }
observers.clear()
}
}
diff --git a/activity/activity/src/main/java/androidx/activity/result/ActivityResultRegistryOwner.kt b/activity/activity/src/main/java/androidx/activity/result/ActivityResultRegistryOwner.kt
index a617ff0..eccf4a0 100644
--- a/activity/activity/src/main/java/androidx/activity/result/ActivityResultRegistryOwner.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/ActivityResultRegistryOwner.kt
@@ -20,8 +20,8 @@
* [ActivityResultCallback] for handling an
* [androidx.activity.result.contract.ActivityResultContract].
*
- * If it is not safe to call [ActivityResultRegistry.register]
- * in the constructor, it is strongly recommended to also implement [ActivityResultCaller].
+ * If it is not safe to call [ActivityResultRegistry.register] in the constructor, it is strongly
+ * recommended to also implement [ActivityResultCaller].
*
* @see ActivityResultRegistry
*/
diff --git a/activity/activity/src/main/java/androidx/activity/result/IntentSenderRequest.kt b/activity/activity/src/main/java/androidx/activity/result/IntentSenderRequest.kt
index 002343a..2027710 100644
--- a/activity/activity/src/main/java/androidx/activity/result/IntentSenderRequest.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/IntentSenderRequest.kt
@@ -25,32 +25,29 @@
/**
* A request for a
- * [androidx.activity.result.contract.ActivityResultContracts.StartIntentSenderForResult]
- * Activity Contract.
+ * [androidx.activity.result.contract.ActivityResultContracts.StartIntentSenderForResult] Activity
+ * Contract.
*/
@SuppressLint("BanParcelableUsage")
-class IntentSenderRequest internal constructor(
- /**
- * The intentSender from this IntentSenderRequest.
- */
+class IntentSenderRequest
+internal constructor(
+ /** The intentSender from this IntentSenderRequest. */
val intentSender: IntentSender,
/**
- * The intent from this IntentSender request. If non-null, this will be provided as the
- * intent parameter to IntentSender#sendIntent.
+ * The intent from this IntentSender request. If non-null, this will be provided as the intent
+ * parameter to IntentSender#sendIntent.
*/
val fillInIntent: Intent? = null,
- /**
- * The flag mask from this IntentSender request.
- */
+ /** The flag mask from this IntentSender request. */
val flagsMask: Int = 0,
- /**
- * The flag values from this IntentSender request.
- */
+ /** The flag values from this IntentSender request. */
val flagsValues: Int = 0,
) : Parcelable {
@Suppress("DEPRECATION")
- internal constructor(parcel: Parcel) : this(
+ internal constructor(
+ parcel: Parcel
+ ) : this(
parcel.readParcelable(IntentSender::class.java.classLoader)!!,
parcel.readParcelable(Intent::class.java.classLoader),
parcel.readInt(),
@@ -68,55 +65,53 @@
dest.writeInt(flagsValues)
}
- /**
- * A builder for constructing [IntentSenderRequest] instances.
- */
+ /** A builder for constructing [IntentSenderRequest] instances. */
class Builder(private val intentSender: IntentSender) {
private var fillInIntent: Intent? = null
private var flagsMask = 0
private var flagsValues = 0
/**
- * Convenience constructor that takes an [PendingIntent] and uses
- * its [IntentSender].
+ * Convenience constructor that takes an [PendingIntent] and uses its [IntentSender].
*
* @param pendingIntent the pendingIntent containing with the intentSender to go in the
- * IntentSenderRequest.
+ * IntentSenderRequest.
*/
constructor(pendingIntent: PendingIntent) : this(pendingIntent.intentSender)
@IntDef(
flag = true,
- value = [
- Intent.FLAG_GRANT_READ_URI_PERMISSION,
- Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
- Intent.FLAG_FROM_BACKGROUND,
- Intent.FLAG_DEBUG_LOG_RESOLUTION,
- Intent.FLAG_EXCLUDE_STOPPED_PACKAGES,
- Intent.FLAG_INCLUDE_STOPPED_PACKAGES,
- Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION,
- Intent.FLAG_GRANT_PREFIX_URI_PERMISSION,
- Intent.FLAG_ACTIVITY_MATCH_EXTERNAL,
- Intent.FLAG_ACTIVITY_NO_HISTORY,
- Intent.FLAG_ACTIVITY_SINGLE_TOP,
- Intent.FLAG_ACTIVITY_NEW_TASK,
- Intent.FLAG_ACTIVITY_MULTIPLE_TASK,
- Intent.FLAG_ACTIVITY_CLEAR_TOP,
- Intent.FLAG_ACTIVITY_FORWARD_RESULT,
- Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP,
- Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS,
- Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT,
- Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED,
- Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY,
- Intent.FLAG_ACTIVITY_NEW_DOCUMENT,
- Intent.FLAG_ACTIVITY_NO_USER_ACTION,
- Intent.FLAG_ACTIVITY_REORDER_TO_FRONT,
- Intent.FLAG_ACTIVITY_NO_ANIMATION,
- Intent.FLAG_ACTIVITY_CLEAR_TASK,
- Intent.FLAG_ACTIVITY_TASK_ON_HOME,
- Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS,
- Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT
- ]
+ value =
+ [
+ Intent.FLAG_GRANT_READ_URI_PERMISSION,
+ Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
+ Intent.FLAG_FROM_BACKGROUND,
+ Intent.FLAG_DEBUG_LOG_RESOLUTION,
+ Intent.FLAG_EXCLUDE_STOPPED_PACKAGES,
+ Intent.FLAG_INCLUDE_STOPPED_PACKAGES,
+ Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION,
+ Intent.FLAG_GRANT_PREFIX_URI_PERMISSION,
+ Intent.FLAG_ACTIVITY_MATCH_EXTERNAL,
+ Intent.FLAG_ACTIVITY_NO_HISTORY,
+ Intent.FLAG_ACTIVITY_SINGLE_TOP,
+ Intent.FLAG_ACTIVITY_NEW_TASK,
+ Intent.FLAG_ACTIVITY_MULTIPLE_TASK,
+ Intent.FLAG_ACTIVITY_CLEAR_TOP,
+ Intent.FLAG_ACTIVITY_FORWARD_RESULT,
+ Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP,
+ Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS,
+ Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT,
+ Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED,
+ Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY,
+ Intent.FLAG_ACTIVITY_NEW_DOCUMENT,
+ Intent.FLAG_ACTIVITY_NO_USER_ACTION,
+ Intent.FLAG_ACTIVITY_REORDER_TO_FRONT,
+ Intent.FLAG_ACTIVITY_NO_ANIMATION,
+ Intent.FLAG_ACTIVITY_CLEAR_TASK,
+ Intent.FLAG_ACTIVITY_TASK_ON_HOME,
+ Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS,
+ Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT
+ ]
)
@Retention(AnnotationRetention.SOURCE)
private annotation class Flag
@@ -124,8 +119,8 @@
/**
* Set the intent for the [IntentSenderRequest].
*
- * @param fillInIntent intent to go in the IntentSenderRequest. If non-null, this
- * will be provided as the intent parameter to IntentSender#sendIntent.
+ * @param fillInIntent intent to go in the IntentSenderRequest. If non-null, this will be
+ * provided as the intent parameter to IntentSender#sendIntent.
* @return This builder.
*/
fun setFillInIntent(fillInIntent: Intent?): Builder {
@@ -137,10 +132,9 @@
* Set the flag mask and flag values for the [IntentSenderRequest].
*
* @param values flagValues to go in the IntentSenderRequest. Desired values for any bits
- * set in flagsMask
+ * set in flagsMask
* @param mask mask to go in the IntentSenderRequest. Intent flags in the original
- * IntentSender that you would like to change.
- *
+ * IntentSender that you would like to change.
* @return This builder.
*/
fun setFlags(@Flag values: Int, mask: Int): Builder {
diff --git a/activity/activity/src/main/java/androidx/activity/result/PickVisualMediaRequest.kt b/activity/activity/src/main/java/androidx/activity/result/PickVisualMediaRequest.kt
index 66f30ef..7b66b55 100644
--- a/activity/activity/src/main/java/androidx/activity/result/PickVisualMediaRequest.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/PickVisualMediaRequest.kt
@@ -25,12 +25,10 @@
* [androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia] Activity Contract.
*
* @param mediaType type to go into the PickVisualMediaRequest
- *
* @return a PickVisualMediaRequest that contains the given input
*/
-fun PickVisualMediaRequest(
- mediaType: VisualMediaType = ImageAndVideo
-) = PickVisualMediaRequest.Builder().setMediaType(mediaType).build()
+fun PickVisualMediaRequest(mediaType: VisualMediaType = ImageAndVideo) =
+ PickVisualMediaRequest.Builder().setMediaType(mediaType).build()
/**
* A request for a
@@ -42,9 +40,7 @@
var mediaType: VisualMediaType = ImageAndVideo
internal set
- /**
- * A builder for constructing [PickVisualMediaRequest] instances.
- */
+ /** A builder for constructing [PickVisualMediaRequest] instances. */
class Builder {
private var mediaType: VisualMediaType = ImageAndVideo
@@ -68,8 +64,7 @@
*
* @return the newly constructed PickVisualMediaRequest.
*/
- fun build(): PickVisualMediaRequest = PickVisualMediaRequest().apply {
- this.mediaType = [email protected]
- }
+ fun build(): PickVisualMediaRequest =
+ PickVisualMediaRequest().apply { this.mediaType = [email protected] }
}
}
diff --git a/activity/activity/src/main/java/androidx/activity/result/contract/ActivityResultContract.kt b/activity/activity/src/main/java/androidx/activity/result/contract/ActivityResultContract.kt
index 4a2164a..41011f0 100644
--- a/activity/activity/src/main/java/androidx/activity/result/contract/ActivityResultContract.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/contract/ActivityResultContract.kt
@@ -19,30 +19,26 @@
import android.content.Intent
/**
- * A contract specifying that an activity can be called with an input of type [I]
- * and produce an output of type [O].
+ * A contract specifying that an activity can be called with an input of type [I] and produce an
+ * output of type [O].
*
* Makes calling an activity for result type-safe.
*
* @see androidx.activity.result.ActivityResultCaller
*/
abstract class ActivityResultContract<I, O> {
- /**
- * Create an intent that can be used for [android.app.Activity.startActivityForResult].
- */
+ /** Create an intent that can be used for [android.app.Activity.startActivityForResult]. */
abstract fun createIntent(context: Context, input: I): Intent
- /**
- * Convert result obtained from [android.app.Activity.onActivityResult] to [O].
- */
+ /** Convert result obtained from [android.app.Activity.onActivityResult] to [O]. */
abstract fun parseResult(resultCode: Int, intent: Intent?): O
/**
- * An optional method you can implement that can be used to potentially provide a result in
- * lieu of starting an activity.
+ * An optional method you can implement that can be used to potentially provide a result in lieu
+ * of starting an activity.
*
- * @return the result wrapped in a [SynchronousResult] or `null` if the call
- * should proceed to start an activity.
+ * @return the result wrapped in a [SynchronousResult] or `null` if the call should proceed to
+ * start an activity.
*/
open fun getSynchronousResult(context: Context, input: I): SynchronousResult<O>? {
return null
diff --git a/activity/activity/src/main/java/androidx/activity/result/contract/ActivityResultContracts.kt b/activity/activity/src/main/java/androidx/activity/result/contract/ActivityResultContracts.kt
index 785c9e5..cd2cc64 100644
--- a/activity/activity/src/main/java/androidx/activity/result/contract/ActivityResultContracts.kt
+++ b/activity/activity/src/main/java/androidx/activity/result/contract/ActivityResultContracts.kt
@@ -44,17 +44,15 @@
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
-/**
- * A collection of some standard activity call contracts, as provided by android.
- */
+/** A collection of some standard activity call contracts, as provided by android. */
class ActivityResultContracts private constructor() {
/**
- * An [ActivityResultContract] that doesn't do any type conversion, taking raw
- * [Intent] as an input and [ActivityResult] as an output.
+ * An [ActivityResultContract] that doesn't do any type conversion, taking raw [Intent] as an
+ * input and [ActivityResult] as an output.
*
- * Can be used with [androidx.activity.result.ActivityResultCaller.registerForActivityResult]
- * to avoid having to manage request codes when calling an activity API for which a
- * type-safe contract is not available.
+ * Can be used with [androidx.activity.result.ActivityResultCaller.registerForActivityResult] to
+ * avoid having to manage request codes when calling an activity API for which a type-safe
+ * contract is not available.
*/
class StartActivityForResult : ActivityResultContract<Intent, ActivityResult>() {
@@ -73,33 +71,30 @@
override fun createIntent(context: Context, input: Intent): Intent = input
- override fun parseResult(
- resultCode: Int,
- intent: Intent?
- ): ActivityResult = ActivityResult(resultCode, intent)
+ override fun parseResult(resultCode: Int, intent: Intent?): ActivityResult =
+ ActivityResult(resultCode, intent)
}
/**
* An [ActivityResultContract] that calls [Activity.startIntentSender].
*
- * This [ActivityResultContract] takes an [IntentSenderRequest], which must be
- * constructed using an [IntentSenderRequest.Builder].
+ * This [ActivityResultContract] takes an [IntentSenderRequest], which must be constructed using
+ * an [IntentSenderRequest.Builder].
*
- * If the call to [Activity.startIntentSenderForResult]
- * throws an [android.content.IntentSender.SendIntentException] the
- * [androidx.activity.result.ActivityResultCallback] will receive an
- * [ActivityResult] with an [Activity.RESULT_CANCELED] `resultCode` and
- * whose intent has the [action][Intent.getAction] of
- * [ACTION_INTENT_SENDER_REQUEST] and an extra [EXTRA_SEND_INTENT_EXCEPTION]
- * that contains the thrown exception.
+ * If the call to [Activity.startIntentSenderForResult] throws an
+ * [android.content.IntentSender.SendIntentException] the
+ * [androidx.activity.result.ActivityResultCallback] will receive an [ActivityResult] with an
+ * [Activity.RESULT_CANCELED] `resultCode` and whose intent has the [action][Intent.getAction]
+ * of [ACTION_INTENT_SENDER_REQUEST] and an extra [EXTRA_SEND_INTENT_EXCEPTION] that contains
+ * the thrown exception.
*/
class StartIntentSenderForResult :
ActivityResultContract<IntentSenderRequest, ActivityResult>() {
companion object {
/**
- * An [Intent] action for making a request via the
- * [Activity.startIntentSenderForResult] API.
+ * An [Intent] action for making a request via the [Activity.startIntentSenderForResult]
+ * API.
*/
const val ACTION_INTENT_SENDER_REQUEST =
"androidx.activity.result.contract.action.INTENT_SENDER_REQUEST"
@@ -121,19 +116,14 @@
}
override fun createIntent(context: Context, input: IntentSenderRequest): Intent {
- return Intent(ACTION_INTENT_SENDER_REQUEST)
- .putExtra(EXTRA_INTENT_SENDER_REQUEST, input)
+ return Intent(ACTION_INTENT_SENDER_REQUEST).putExtra(EXTRA_INTENT_SENDER_REQUEST, input)
}
- override fun parseResult(
- resultCode: Int,
- intent: Intent?
- ): ActivityResult = ActivityResult(resultCode, intent)
+ override fun parseResult(resultCode: Int, intent: Intent?): ActivityResult =
+ ActivityResult(resultCode, intent)
}
- /**
- * An [ActivityResultContract] to [request permissions][Activity.requestPermissions]
- */
+ /** An [ActivityResultContract] to [request permissions][Activity.requestPermissions] */
class RequestMultiplePermissions :
ActivityResultContract<Array<String>, Map<String, @JvmSuppressWildcards Boolean>>() {
@@ -144,9 +134,8 @@
*
* Caller must provide a `String[]` extra [EXTRA_PERMISSIONS]
*
- * Result will be delivered via [Activity.onActivityResult] with
- * `String[]` [EXTRA_PERMISSIONS] and `int[]`
- * [EXTRA_PERMISSION_GRANT_RESULTS], similar to
+ * Result will be delivered via [Activity.onActivityResult] with `String[]`
+ * [EXTRA_PERMISSIONS] and `int[]` [EXTRA_PERMISSION_GRANT_RESULTS], similar to
* [Activity.onRequestPermissionsResult]
*
* @see Activity.requestPermissions
@@ -186,36 +175,29 @@
if (input.isEmpty()) {
return SynchronousResult(emptyMap())
}
- val allGranted = input.all { permission ->
- ContextCompat.checkSelfPermission(
- context,
- permission
- ) == PackageManager.PERMISSION_GRANTED
- }
+ val allGranted =
+ input.all { permission ->
+ ContextCompat.checkSelfPermission(context, permission) ==
+ PackageManager.PERMISSION_GRANTED
+ }
return if (allGranted) {
SynchronousResult(input.associate { it to true })
} else null
}
- override fun parseResult(
- resultCode: Int,
- intent: Intent?
- ): Map<String, Boolean> {
+ override fun parseResult(resultCode: Int, intent: Intent?): Map<String, Boolean> {
if (resultCode != Activity.RESULT_OK) return emptyMap()
if (intent == null) return emptyMap()
val permissions = intent.getStringArrayExtra(EXTRA_PERMISSIONS)
val grantResults = intent.getIntArrayExtra(EXTRA_PERMISSION_GRANT_RESULTS)
if (grantResults == null || permissions == null) return emptyMap()
- val grantState = grantResults.map { result ->
- result == PackageManager.PERMISSION_GRANTED
- }
+ val grantState =
+ grantResults.map { result -> result == PackageManager.PERMISSION_GRANTED }
return permissions.filterNotNull().zip(grantState).toMap()
}
}
- /**
- * An [ActivityResultContract] to [request a permission][Activity.requestPermissions]
- */
+ /** An [ActivityResultContract] to [request a permission][Activity.requestPermissions] */
class RequestPermission : ActivityResultContract<String, Boolean>() {
override fun createIntent(context: Context, input: String): Intent {
return RequestMultiplePermissions.createIntent(arrayOf(input))
@@ -226,19 +208,17 @@
if (intent == null || resultCode != Activity.RESULT_OK) return false
val grantResults =
intent.getIntArrayExtra(RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS)
- return grantResults?.any { result ->
- result == PackageManager.PERMISSION_GRANTED
- } == true
+ return grantResults?.any { result -> result == PackageManager.PERMISSION_GRANTED } ==
+ true
}
override fun getSynchronousResult(
context: Context,
input: String
): SynchronousResult<Boolean>? {
- val granted = ContextCompat.checkSelfPermission(
- context,
- input
- ) == PackageManager.PERMISSION_GRANTED
+ val granted =
+ ContextCompat.checkSelfPermission(context, input) ==
+ PackageManager.PERMISSION_GRANTED
return if (granted) {
SynchronousResult(true)
} else {
@@ -249,12 +229,11 @@
}
/**
- * An [ActivityResultContract] to
- * [take small a picture][MediaStore.ACTION_IMAGE_CAPTURE] preview, returning it as a
- * [Bitmap].
+ * An [ActivityResultContract] to [take small a picture][MediaStore.ACTION_IMAGE_CAPTURE]
+ * preview, returning it as a [Bitmap].
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
open class TakePicturePreview : ActivityResultContract<Void?, Bitmap?>() {
@CallSuper
@@ -274,20 +253,18 @@
}
/**
- * An [ActivityResultContract] to
- * [take a picture][MediaStore.ACTION_IMAGE_CAPTURE] saving it into the provided
- * content-[Uri].
+ * An [ActivityResultContract] to [take a picture][MediaStore.ACTION_IMAGE_CAPTURE] saving it
+ * into the provided content-[Uri].
*
* Returns `true` if the image was saved into the given [Uri].
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
open class TakePicture : ActivityResultContract<Uri, Boolean>() {
@CallSuper
override fun createIntent(context: Context, input: Uri): Intent {
- return Intent(MediaStore.ACTION_IMAGE_CAPTURE)
- .putExtra(MediaStore.EXTRA_OUTPUT, input)
+ return Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, input)
}
final override fun getSynchronousResult(
@@ -302,15 +279,13 @@
}
/**
- * An [ActivityResultContract] to
- * [take a video][MediaStore.ACTION_VIDEO_CAPTURE] saving it into the provided
- * content-[Uri].
+ * An [ActivityResultContract] to [take a video][MediaStore.ACTION_VIDEO_CAPTURE] saving it into
+ * the provided content-[Uri].
*
* Returns a thumbnail.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
- *
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
@Deprecated(
"""The thumbnail bitmap is rarely returned and is not a good signal to determine
@@ -319,8 +294,7 @@
open class TakeVideo : ActivityResultContract<Uri, Bitmap?>() {
@CallSuper
override fun createIntent(context: Context, input: Uri): Intent {
- return Intent(MediaStore.ACTION_VIDEO_CAPTURE)
- .putExtra(MediaStore.EXTRA_OUTPUT, input)
+ return Intent(MediaStore.ACTION_VIDEO_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, input)
}
final override fun getSynchronousResult(
@@ -335,20 +309,18 @@
}
/**
- * An [ActivityResultContract] to
- * [take a video][MediaStore.ACTION_VIDEO_CAPTURE] saving it into the provided
- * content-[Uri].
+ * An [ActivityResultContract] to [take a video][MediaStore.ACTION_VIDEO_CAPTURE] saving it into
+ * the provided content-[Uri].
*
* Returns `true` if the video was saved into the given [Uri].
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
open class CaptureVideo : ActivityResultContract<Uri, Boolean>() {
@CallSuper
override fun createIntent(context: Context, input: Uri): Intent {
- return Intent(MediaStore.ACTION_VIDEO_CAPTURE)
- .putExtra(MediaStore.EXTRA_OUTPUT, input)
+ return Intent(MediaStore.ACTION_VIDEO_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, input)
}
final override fun getSynchronousResult(
@@ -363,8 +335,7 @@
}
/**
- * An [ActivityResultContract] to request the user to pick a contact from the contacts
- * app.
+ * An [ActivityResultContract] to request the user to pick a contact from the contacts app.
*
* The result is a `content:` [Uri].
*
@@ -381,16 +352,15 @@
}
/**
- * An [ActivityResultContract] to prompt the user to pick a piece of content, receiving
- * a `content://` [Uri] for that content that allows you to use
- * [android.content.ContentResolver.openInputStream] to access the raw data. By
- * default, this adds [Intent.CATEGORY_OPENABLE] to only return content that can be
- * represented as a stream.
+ * An [ActivityResultContract] to prompt the user to pick a piece of content, receiving a
+ * `content://` [Uri] for that content that allows you to use
+ * [android.content.ContentResolver.openInputStream] to access the raw data. By default, this
+ * adds [Intent.CATEGORY_OPENABLE] to only return content that can be represented as a stream.
*
* The input is the mime type to filter by, e.g. `image/\*`.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
open class GetContent : ActivityResultContract<String, Uri?>() {
@CallSuper
@@ -411,16 +381,15 @@
}
/**
- * An [ActivityResultContract] to prompt the user to pick one or more a pieces of
- * content, receiving a `content://` [Uri] for each piece of content that allows
- * you to use [android.content.ContentResolver.openInputStream]
- * to access the raw data. By default, this adds [Intent.CATEGORY_OPENABLE] to only
- * return content that can be represented as a stream.
+ * An [ActivityResultContract] to prompt the user to pick one or more a pieces of content,
+ * receiving a `content://` [Uri] for each piece of content that allows you to use
+ * [android.content.ContentResolver.openInputStream] to access the raw data. By default, this
+ * adds [Intent.CATEGORY_OPENABLE] to only return content that can be represented as a stream.
*
* The input is the mime type to filter by, e.g. `image/\*`.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
open class GetMultipleContents :
ActivityResultContract<String, List<@JvmSuppressWildcards Uri>>() {
@@ -438,9 +407,8 @@
): SynchronousResult<List<Uri>>? = null
final override fun parseResult(resultCode: Int, intent: Intent?): List<Uri> {
- return intent.takeIf {
- resultCode == Activity.RESULT_OK
- }?.getClipDataUris() ?: emptyList()
+ return intent.takeIf { resultCode == Activity.RESULT_OK }?.getClipDataUris()
+ ?: emptyList()
}
internal companion object {
@@ -448,9 +416,7 @@
// Use a LinkedHashSet to maintain any ordering that may be
// present in the ClipData
val resultSet = LinkedHashSet<Uri>()
- data?.let { data ->
- resultSet.add(data)
- }
+ data?.let { data -> resultSet.add(data) }
val clipData = clipData
if (clipData == null && resultSet.isEmpty()) {
return emptyList()
@@ -468,13 +434,13 @@
}
/**
- * An [ActivityResultContract] to prompt the user to open a document, receiving its
- * contents as a `file:/http:/content:` [Uri].
+ * An [ActivityResultContract] to prompt the user to open a document, receiving its contents as
+ * a `file:/http:/content:` [Uri].
*
* The input is the mime types to filter by, e.g. `image/\*`.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*
* @see DocumentsContract
*/
@@ -497,13 +463,13 @@
}
/**
- * An [ActivityResultContract] to prompt the user to open (possibly multiple)
- * documents, receiving their contents as `file:/http:/content:` [Uri]s.
+ * An [ActivityResultContract] to prompt the user to open (possibly multiple) documents,
+ * receiving their contents as `file:/http:/content:` [Uri]s.
*
* The input is the mime types to filter by, e.g. `image/\*`.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*
* @see DocumentsContract
*/
@@ -523,24 +489,21 @@
): SynchronousResult<List<Uri>>? = null
final override fun parseResult(resultCode: Int, intent: Intent?): List<Uri> {
- return intent.takeIf {
- resultCode == Activity.RESULT_OK
- }?.getClipDataUris() ?: emptyList()
+ return intent.takeIf { resultCode == Activity.RESULT_OK }?.getClipDataUris()
+ ?: emptyList()
}
}
/**
- * An [ActivityResultContract] to prompt the user to select a directory, returning the
- * user selection as a [Uri]. Apps can fully manage documents within the returned
- * directory.
+ * An [ActivityResultContract] to prompt the user to select a directory, returning the user
+ * selection as a [Uri]. Apps can fully manage documents within the returned directory.
*
* The input is an optional [Uri] of the initial starting location.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*
* @see Intent.ACTION_OPEN_DOCUMENT_TREE
- *
* @see DocumentsContract.buildDocumentUriUsingTree
* @see DocumentsContract.buildChildDocumentsUriUsingTree
*/
@@ -566,18 +529,16 @@
}
/**
- * An [ActivityResultContract] to prompt the user to select a path for creating a new
- * document of the given [mimeType], returning the `content:` [Uri] of the item that was
- * created.
+ * An [ActivityResultContract] to prompt the user to select a path for creating a new document
+ * of the given [mimeType], returning the `content:` [Uri] of the item that was created.
*
* The input is the suggested name for the new file.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
- open class CreateDocument(
- private val mimeType: String
- ) : ActivityResultContract<String, Uri?>() {
+ open class CreateDocument(private val mimeType: String) :
+ ActivityResultContract<String, Uri?>() {
@Deprecated(
"Using a wildcard mime type with CreateDocument is not recommended as it breaks " +
@@ -607,28 +568,28 @@
/**
* An [ActivityResultContract] to use the
- * [Photo Picker](https://developer.android.com/training/data-storage/shared/photopicker)
- * to select a single image, video, or other type of visual media.
+ * [Photo Picker](https://developer.android.com/training/data-storage/shared/photopicker) to
+ * select a single image, video, or other type of visual media.
*
* This contract always prefers the system framework provided Photo Picker available via
- * [MediaStore.ACTION_PICK_IMAGES] when it is available, but will also provide a fallback
- * on devices that it is not available to ensure a consistent API surface across all
- * Android API 19 or higher devices.
+ * [MediaStore.ACTION_PICK_IMAGES] when it is available, but will also provide a fallback on
+ * devices that it is not available to ensure a consistent API surface across all Android API 19
+ * or higher devices.
*
* The priority order for handling the Photo Picker is:
* 1. The system framework provided [MediaStore.ACTION_PICK_IMAGES].
* - An OEM can provide a system app that implements [ACTION_SYSTEM_FALLBACK_PICK_IMAGES] to
- * provide a consistent Photo Picker to older devices.
- * - [Intent.ACTION_OPEN_DOCUMENT] is used as a final fallback on all Android API 19 or
- * higher devices.
+ * provide a consistent Photo Picker to older devices.
+ * - [Intent.ACTION_OPEN_DOCUMENT] is used as a final fallback on all Android API 19 or higher
+ * devices.
*
* The input is a [PickVisualMediaRequest].
*
* The output is a `Uri` when the user has selected a media or `null` when the user hasn't
* selected any item. Keep in mind that `Uri` returned by the photo picker isn't writable.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
open class PickVisualMedia : ActivityResultContract<PickVisualMediaRequest, Uri?>() {
companion object {
@@ -641,8 +602,9 @@
*/
@SuppressLint("ClassVerificationFailure", "NewApi")
@Deprecated(
- message = "This method is deprecated in favor of isPhotoPickerAvailable(context) " +
- "to support the picker provided by updatable system apps",
+ message =
+ "This method is deprecated in favor of isPhotoPickerAvailable(context) " +
+ "to support the picker provided by updatable system apps",
replaceWith = ReplaceWith("isPhotoPickerAvailable(context)")
)
@JvmStatic
@@ -651,17 +613,16 @@
}
/**
- * In cases where the system framework provided [MediaStore.ACTION_PICK_IMAGES]
- * Photo Picker cannot be implemented, OEMs or system apps can provide a consistent
- * Photo Picker experience to those devices by creating an Activity that handles
- * this action. This app must also include [Intent.CATEGORY_DEFAULT] in the activity's
- * intent filter.
+ * In cases where the system framework provided [MediaStore.ACTION_PICK_IMAGES] Photo
+ * Picker cannot be implemented, OEMs or system apps can provide a consistent Photo
+ * Picker experience to those devices by creating an Activity that handles this action.
+ * This app must also include [Intent.CATEGORY_DEFAULT] in the activity's intent filter.
*
- * Only system apps can implement this action - any non-system apps will be ignored
- * when searching for the activities that handle this Intent.
+ * Only system apps can implement this action - any non-system apps will be ignored when
+ * searching for the activities that handle this Intent.
*
- * Note: this should not be used directly, instead relying on the selection logic
- * done by [createIntent] to create the correct Intent for the current device.
+ * Note: this should not be used directly, instead relying on the selection logic done
+ * by [createIntent] to create the correct Intent for the current device.
*/
@Suppress("ActionValue") /* Don't include SYSTEM_FALLBACK in the action */
const val ACTION_SYSTEM_FALLBACK_PICK_IMAGES =
@@ -669,13 +630,13 @@
/**
* Extra that will be sent by [PickMultipleVisualMedia] to an Activity that handles
- * [ACTION_SYSTEM_FALLBACK_PICK_IMAGES] that indicates that maximum number of photos
- * the user should select.
+ * [ACTION_SYSTEM_FALLBACK_PICK_IMAGES] that indicates that maximum number of photos the
+ * user should select.
*
* If this extra is not present, only a single photo should be selectable.
*
- * If this extra is present but equal to [Int.MAX_VALUE], then no limit should
- * be enforced.
+ * If this extra is present but equal to [Int.MAX_VALUE], then no limit should be
+ * enforced.
*/
@Suppress("ActionValue") /* Don't include SYSTEM_FALLBACK in the extra */
const val EXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX =
@@ -688,13 +649,14 @@
/**
* Check if the current device has support for the photo picker by checking the running
- * Android version, the SDK extension version or the picker provided by
- * a system app implementing [ACTION_SYSTEM_FALLBACK_PICK_IMAGES].
+ * Android version, the SDK extension version or the picker provided by a system app
+ * implementing [ACTION_SYSTEM_FALLBACK_PICK_IMAGES].
*/
@SuppressLint("ClassVerificationFailure", "NewApi")
@JvmStatic
fun isPhotoPickerAvailable(context: Context): Boolean {
- return isSystemPickerAvailable() || isSystemFallbackPickerAvailable(context) ||
+ return isSystemPickerAvailable() ||
+ isSystemFallbackPickerAvailable(context) ||
isGmsPickerAvailable(context)
}
@@ -757,24 +719,16 @@
}
}
- /**
- * Represents filter input type accepted by the photo picker.
- */
+ /** Represents filter input type accepted by the photo picker. */
sealed interface VisualMediaType
- /**
- * [VisualMediaType] object used to filter images only when using the photo picker.
- */
+ /** [VisualMediaType] object used to filter images only when using the photo picker. */
object ImageOnly : VisualMediaType
- /**
- * [VisualMediaType] object used to filter video only when using the photo picker.
- */
+ /** [VisualMediaType] object used to filter video only when using the photo picker. */
object VideoOnly : VisualMediaType
- /**
- * [VisualMediaType] object used to filter images and video when using the photo picker.
- */
+ /** [VisualMediaType] object used to filter images and video when using the photo picker. */
object ImageAndVideo : VisualMediaType
/**
@@ -826,33 +780,35 @@
): SynchronousResult<Uri?>? = null
final override fun parseResult(resultCode: Int, intent: Intent?): Uri? {
- return intent.takeIf { resultCode == Activity.RESULT_OK }?.run {
- // Check both the data URI and ClipData since the GMS picker
- // only returns results through getClipDataUris()
- data ?: getClipDataUris().firstOrNull()
- }
+ return intent
+ .takeIf { resultCode == Activity.RESULT_OK }
+ ?.run {
+ // Check both the data URI and ClipData since the GMS picker
+ // only returns results through getClipDataUris()
+ data ?: getClipDataUris().firstOrNull()
+ }
}
}
/**
* An [ActivityResultContract] to use the
- * [Photo Picker](https://developer.android.com/training/data-storage/shared/photopicker)
- * to select a single image, video, or other type of visual media.
+ * [Photo Picker](https://developer.android.com/training/data-storage/shared/photopicker) to
+ * select a single image, video, or other type of visual media.
*
* This contract always prefers the system framework provided Photo Picker available via
- * [MediaStore.ACTION_PICK_IMAGES] when it is available, but will also provide a fallback
- * on devices that it is not available to provide a consistent API surface across all
- * Android API 19 or higher devices.
+ * [MediaStore.ACTION_PICK_IMAGES] when it is available, but will also provide a fallback on
+ * devices that it is not available to provide a consistent API surface across all Android API
+ * 19 or higher devices.
*
* The priority order for handling the Photo Picker is:
* 1. The system framework provided [MediaStore.ACTION_PICK_IMAGES].
* - An OEM can provide a system app that implements
- * [PickVisualMedia.ACTION_SYSTEM_FALLBACK_PICK_IMAGES] to provide a consistent Photo Picker
- * to older devices. These system apps may handle the
- * [PickVisualMedia.EXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX] extra to respect the
- * [maxItems] passed to this contract.
- * - [Intent.ACTION_OPEN_DOCUMENT] is used as a final fallback on all Android API 19 or
- * higher devices. This Intent does not allow limiting the max items the user selects.
+ * [PickVisualMedia.ACTION_SYSTEM_FALLBACK_PICK_IMAGES] to provide a consistent Photo Picker
+ * to older devices. These system apps may handle the
+ * [PickVisualMedia.EXTRA_SYSTEM_FALLBACK_PICK_IMAGES_MAX] extra to respect the [maxItems]
+ * passed to this contract.
+ * - [Intent.ACTION_OPEN_DOCUMENT] is used as a final fallback on all Android API 19 or higher
+ * devices. This Intent does not allow limiting the max items the user selects.
*
* The constructor accepts one parameter [maxItems] to limit the number of selectable items when
* using the photo picker to return.
@@ -862,17 +818,14 @@
* The output is a list `Uri` of the selected media. It can be empty if the user hasn't selected
* any items. Keep in mind that `Uri` returned by the photo picker aren't writable.
*
- * This can be extended to override [createIntent] if you wish to pass additional
- * extras to the Intent created by `super.createIntent()`.
+ * This can be extended to override [createIntent] if you wish to pass additional extras to the
+ * Intent created by `super.createIntent()`.
*/
- open class PickMultipleVisualMedia(
- private val maxItems: Int = getMaxItems()
- ) : ActivityResultContract<PickVisualMediaRequest, List<@JvmSuppressWildcards Uri>>() {
+ open class PickMultipleVisualMedia(private val maxItems: Int = getMaxItems()) :
+ ActivityResultContract<PickVisualMediaRequest, List<@JvmSuppressWildcards Uri>>() {
init {
- require(maxItems > 1) {
- "Max items must be higher than 1"
- }
+ require(maxItems > 1) { "Max items must be higher than 1" }
}
@CallSuper
@@ -926,27 +879,26 @@
): SynchronousResult<List<@JvmSuppressWildcards Uri>>? = null
final override fun parseResult(resultCode: Int, intent: Intent?): List<Uri> {
- return intent.takeIf {
- resultCode == Activity.RESULT_OK
- }?.getClipDataUris() ?: emptyList()
+ return intent.takeIf { resultCode == Activity.RESULT_OK }?.getClipDataUris()
+ ?: emptyList()
}
internal companion object {
/**
* The system photo picker has a maximum limit of selectable items returned by
- * [MediaStore.getPickImagesMaxLimit()]
- * On devices supporting picker provided via [ACTION_SYSTEM_FALLBACK_PICK_IMAGES],
- * the limit may be ignored if it's higher than the allowed limit.
- * On devices not supporting the photo picker, the limit is ignored.
+ * [MediaStore.getPickImagesMaxLimit()] On devices supporting picker provided via
+ * [ACTION_SYSTEM_FALLBACK_PICK_IMAGES], the limit may be ignored if it's higher than
+ * the allowed limit. On devices not supporting the photo picker, the limit is ignored.
*
* @see MediaStore.EXTRA_PICK_IMAGES_MAX
*/
@SuppressLint("NewApi", "ClassVerificationFailure")
- internal fun getMaxItems() = if (PickVisualMedia.isSystemPickerAvailable()) {
- MediaStore.getPickImagesMaxLimit()
- } else {
- Integer.MAX_VALUE
- }
+ internal fun getMaxItems() =
+ if (PickVisualMedia.isSystemPickerAvailable()) {
+ MediaStore.getPickImagesMaxLimit()
+ } else {
+ Integer.MAX_VALUE
+ }
}
}
}
diff --git a/activity/integration-tests/baselineprofile/src/main/java/androidx/activity/integration/testapp/baselineprofiles/BaselineProfileTest.kt b/activity/integration-tests/baselineprofile/src/main/java/androidx/activity/integration/testapp/baselineprofiles/BaselineProfileTest.kt
index d9a4153..f6b6986 100644
--- a/activity/integration-tests/baselineprofile/src/main/java/androidx/activity/integration/testapp/baselineprofiles/BaselineProfileTest.kt
+++ b/activity/integration-tests/baselineprofile/src/main/java/androidx/activity/integration/testapp/baselineprofiles/BaselineProfileTest.kt
@@ -30,8 +30,7 @@
@SdkSuppress(minSdkVersion = 28)
class BaselineProfileTest {
- @get:Rule
- val baselineRule = BaselineProfileRule()
+ @get:Rule val baselineRule = BaselineProfileRule()
@Test
fun startupBaselineProfile() {
@@ -48,9 +47,7 @@
}
companion object {
- private const val PACKAGE_NAME =
- "androidx.activity.integration.testapp"
- private const val ACTION =
- "androidx.activity.integration.testapp.EDGE_TO_EDGE_ACTIVITY"
+ private const val PACKAGE_NAME = "androidx.activity.integration.testapp"
+ private const val ACTION = "androidx.activity.integration.testapp.EDGE_TO_EDGE_ACTIVITY"
}
}
diff --git a/activity/integration-tests/macrobenchmark-target/src/main/java/androidx/activity/integration/macrobenchmark/target/OnBackPressedDispatcherInOnCreateActivity.kt b/activity/integration-tests/macrobenchmark-target/src/main/java/androidx/activity/integration/macrobenchmark/target/OnBackPressedDispatcherInOnCreateActivity.kt
index 8a38baa..21e3a20 100644
--- a/activity/integration-tests/macrobenchmark-target/src/main/java/androidx/activity/integration/macrobenchmark/target/OnBackPressedDispatcherInOnCreateActivity.kt
+++ b/activity/integration-tests/macrobenchmark-target/src/main/java/androidx/activity/integration/macrobenchmark/target/OnBackPressedDispatcherInOnCreateActivity.kt
@@ -19,8 +19,7 @@
import android.os.Bundle
import androidx.activity.ComponentActivity
-class OnBackPressedDispatcherInOnCreateActivity :
- ComponentActivity(R.layout.main_activity) {
+class OnBackPressedDispatcherInOnCreateActivity : ComponentActivity(R.layout.main_activity) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onBackPressedDispatcher
diff --git a/activity/integration-tests/macrobenchmark/src/main/java/androidx/activity/integration/macrobenchmark/ActivityStartBenchmark.kt b/activity/integration-tests/macrobenchmark/src/main/java/androidx/activity/integration/macrobenchmark/ActivityStartBenchmark.kt
index f28ba33..70298ee 100644
--- a/activity/integration-tests/macrobenchmark/src/main/java/androidx/activity/integration/macrobenchmark/ActivityStartBenchmark.kt
+++ b/activity/integration-tests/macrobenchmark/src/main/java/androidx/activity/integration/macrobenchmark/ActivityStartBenchmark.kt
@@ -29,18 +29,19 @@
@RunWith(AndroidJUnit4::class)
class ActivityStartBenchmark {
- @get:Rule
- val benchmarkRule = MacrobenchmarkRule()
+ @get:Rule val benchmarkRule = MacrobenchmarkRule()
@Test
- fun startup() = benchmarkRule.measureStartup(
- compilationMode = CompilationMode.DEFAULT,
- startupMode = StartupMode.COLD,
- packageName = "androidx.activity.integration.macrobenchmark.target",
- metrics = listOf(StartupTimingMetric()),
- iterations = 10,
- ) {
- action = "androidx.compose.integration.macrobenchmark" +
- ".target.ON_BACK_PRESSED_DISPATCHER_IN_ON_CREATE_ACTIVITY"
- }
+ fun startup() =
+ benchmarkRule.measureStartup(
+ compilationMode = CompilationMode.DEFAULT,
+ startupMode = StartupMode.COLD,
+ packageName = "androidx.activity.integration.macrobenchmark.target",
+ metrics = listOf(StartupTimingMetric()),
+ iterations = 10,
+ ) {
+ action =
+ "androidx.compose.integration.macrobenchmark" +
+ ".target.ON_BACK_PRESSED_DISPATCHER_IN_ON_CREATE_ACTIVITY"
+ }
}
diff --git a/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/EdgeToEdgeActivity.kt b/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/EdgeToEdgeActivity.kt
index f3f23d6..6f1d73d 100644
--- a/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/EdgeToEdgeActivity.kt
+++ b/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/EdgeToEdgeActivity.kt
@@ -49,21 +49,23 @@
// API 29+: Transparent on gesture nav, Auto scrim on 3-button nav (same as default).
// API 23-28: Yellow bars.
// API 21,22: Dark scrim (system default).
- val style = SystemBarStyle.auto(
- lightScrim = Color.argb(0x64, 0xff, 0xeb, 0x3b),
- darkScrim = Color.argb(0x64, 0x4a, 0x14, 0x8c)
- )
+ val style =
+ SystemBarStyle.auto(
+ lightScrim = Color.argb(0x64, 0xff, 0xeb, 0x3b),
+ darkScrim = Color.argb(0x64, 0x4a, 0x14, 0x8c)
+ )
enableEdgeToEdge(statusBarStyle = style, navigationBarStyle = style)
}
findViewById<View>(R.id.custom_config).setOnClickListener {
// API 29+: Transparent on gesture nav, Auto scrim on 3-button nav (same as default).
// API 23-28: Yellow bars.
// API 21,22: Dark scrim (system default).
- val style = SystemBarStyle.auto(
- lightScrim = Color.argb(0x64, 0xff, 0xeb, 0x3b),
- darkScrim = Color.argb(0x64, 0x4a, 0x14, 0x8c),
- detectDarkMode = { false }
- )
+ val style =
+ SystemBarStyle.auto(
+ lightScrim = Color.argb(0x64, 0xff, 0xeb, 0x3b),
+ darkScrim = Color.argb(0x64, 0x4a, 0x14, 0x8c),
+ detectDarkMode = { false }
+ )
enableEdgeToEdge(statusBarStyle = style, navigationBarStyle = style)
}
findViewById<View>(R.id.transparent_config).setOnClickListener {
@@ -75,18 +77,17 @@
findViewById<View>(R.id.purple_config).setOnClickListener {
// API 23+: Purple.
// API 21,22: Dark scrim (system default).
- val style = SystemBarStyle.dark(
- scrim = Color.argb(0x64, 0x4a, 0x14, 0x8c)
- )
+ val style = SystemBarStyle.dark(scrim = Color.argb(0x64, 0x4a, 0x14, 0x8c))
enableEdgeToEdge(statusBarStyle = style, navigationBarStyle = style)
}
findViewById<View>(R.id.yellow_config).setOnClickListener {
// API 23+: Yellow.
// API 21,22: Dark scrim (system default).
- val style = SystemBarStyle.light(
- scrim = Color.argb(0x64, 0xff, 0xeb, 0x3b),
- darkScrim = Color.rgb(0xf5, 0x7f, 0x17)
- )
+ val style =
+ SystemBarStyle.light(
+ scrim = Color.argb(0x64, 0xff, 0xeb, 0x3b),
+ darkScrim = Color.rgb(0xf5, 0x7f, 0x17)
+ )
enableEdgeToEdge(statusBarStyle = style, navigationBarStyle = style)
}
findViewById<View>(R.id.light_mode).setOnClickListener { setDarkMode(false) }
@@ -109,9 +110,7 @@
return AlertDialog.Builder(requireContext())
.setTitle("Demo Dialog")
.setMessage("Hello, world!")
- .setPositiveButton(android.R.string.ok, { dialog, _ ->
- dialog.dismiss()
- })
+ .setPositiveButton(android.R.string.ok, { dialog, _ -> dialog.dismiss() })
.create()
}
}
diff --git a/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/MainActivity.kt b/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/MainActivity.kt
index 819a7dd..b0329e8 100644
--- a/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/MainActivity.kt
+++ b/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/MainActivity.kt
@@ -54,31 +54,22 @@
class MainActivity : ComponentActivity() {
- val requestLocation = registerForActivityResult(
- RequestPermission(), ACCESS_FINE_LOCATION
- ) { isGranted ->
- toast("Location granted: $isGranted")
- }
+ val requestLocation =
+ registerForActivityResult(RequestPermission(), ACCESS_FINE_LOCATION) { isGranted ->
+ toast("Location granted: $isGranted")
+ }
- val takePicturePreview = registerForActivityResult(TakePicturePreview()) { bitmap ->
- toast("Got picture: $bitmap")
- }
+ val takePicturePreview =
+ registerForActivityResult(TakePicturePreview()) { bitmap -> toast("Got picture: $bitmap") }
- val takePicture = registerForActivityResult(TakePicture()) { success ->
- toast("Got picture: $success")
- }
+ val takePicture =
+ registerForActivityResult(TakePicture()) { success -> toast("Got picture: $success") }
- val captureVideo: ActivityResultLauncher<Uri> = registerForActivityResult(
- CaptureVideo()
- ) { success ->
- toast("Got video: $success")
- }
+ val captureVideo: ActivityResultLauncher<Uri> =
+ registerForActivityResult(CaptureVideo()) { success -> toast("Got video: $success") }
- val getContent: ActivityResultLauncher<String> = registerForActivityResult(
- GetContent()
- ) { uri ->
- toast("Got image: $uri")
- }
+ val getContent: ActivityResultLauncher<String> =
+ registerForActivityResult(GetContent()) { uri -> toast("Got image: $uri") }
lateinit var pickVisualMedia: ActivityResultLauncher<PickVisualMediaRequest>
@@ -88,48 +79,39 @@
lateinit var openDocuments: ActivityResultLauncher<Array<String>>
- private val intentSender = registerForActivityResult(
- ActivityResultContracts
- .StartIntentSenderForResult()
- ) {
- toast("Received intent sender callback")
- }
+ private val intentSender =
+ registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
+ toast("Received intent sender callback")
+ }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- pickVisualMedia = registerForActivityResult(PickVisualMedia()) { uri ->
- toast("Got image: $uri")
- }
+ pickVisualMedia =
+ registerForActivityResult(PickVisualMedia()) { uri -> toast("Got image: $uri") }
pickMultipleVisualMedia =
registerForActivityResult(PickMultipleVisualMedia(5)) { uris ->
var media = ""
- uris.forEach {
- media += "uri: $it \n"
- }
+ uris.forEach { media += "uri: $it \n" }
toast("Got media files: $media")
}
- createDocument = registerForActivityResult(CreateDocument("image/png")) { uri ->
- toast("Created document: $uri")
- }
- openDocuments = registerForActivityResult(OpenMultipleDocuments()) { uris ->
- var docs = ""
- uris.forEach {
- docs += "uri: $it \n"
+ createDocument =
+ registerForActivityResult(CreateDocument("image/png")) { uri ->
+ toast("Created document: $uri")
}
- toast("Got documents: $docs")
- }
+ openDocuments =
+ registerForActivityResult(OpenMultipleDocuments()) { uris ->
+ var docs = ""
+ uris.forEach { docs += "uri: $it \n" }
+ toast("Got documents: $docs")
+ }
setContentView {
add(::LinearLayout) {
orientation = VERTICAL
- button("Request location permission") {
- requestLocation.launch()
- }
- button("Get picture thumbnail") {
- takePicturePreview.launch()
- }
+ button("Request location permission") { requestLocation.launch() }
+ button("Get picture thumbnail") { takePicturePreview.launch() }
button("Take pic") {
val file = File(filesDir, "image")
val uri = FileProvider.getUriForFile(this@MainActivity, packageName, file)
@@ -140,13 +122,9 @@
val uri = FileProvider.getUriForFile(this@MainActivity, packageName, file)
captureVideo.launch(uri)
}
- button("Pick an image (w/ GET_CONTENT)") {
- getContent.launch("image/*")
- }
+ button("Pick an image (w/ GET_CONTENT)") { getContent.launch("image/*") }
button("Pick an image (w/ photo picker)") {
- pickVisualMedia.launch(
- PickVisualMediaRequest(PickVisualMedia.ImageOnly)
- )
+ pickVisualMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageOnly))
}
button("Pick a GIF (w/ photo picker)") {
pickVisualMedia.launch(
@@ -158,24 +136,23 @@
PickVisualMediaRequest(PickVisualMedia.ImageAndVideo)
)
}
- button("Create document") {
- createDocument.launch("Temp")
- }
- button("Open documents") {
- openDocuments.launch(arrayOf("*/*"))
- }
+ button("Create document") { createDocument.launch("Temp") }
+ button("Open documents") { openDocuments.launch(arrayOf("*/*")) }
button("Start IntentSender") {
- val request = IntentSenderRequest.Builder(
- PendingIntent.getActivity(
- context,
- 0,
- Intent(MediaStore.ACTION_IMAGE_CAPTURE),
- PendingIntent.FLAG_IMMUTABLE
- )
- )
- .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP,
- 1)
- .build()
+ val request =
+ IntentSenderRequest.Builder(
+ PendingIntent.getActivity(
+ context,
+ 0,
+ Intent(MediaStore.ACTION_IMAGE_CAPTURE),
+ PendingIntent.FLAG_IMMUTABLE
+ )
+ )
+ .setFlags(
+ Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP,
+ 1
+ )
+ .build()
intentSender.launch(request)
}
}
@@ -187,8 +164,7 @@
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
-inline fun Activity.setContentView(ui: ViewManager.() -> Unit) =
- ActivityViewManager(this).apply(ui)
+inline fun Activity.setContentView(ui: ViewManager.() -> Unit) = ActivityViewManager(this).apply(ui)
class ActivityViewManager(val activity: Activity) : ViewManager {
override fun addView(p0: View?, p1: ViewGroup.LayoutParams?) {
@@ -203,11 +179,14 @@
TODO("not implemented")
}
}
-val ViewManager.context get() = when (this) {
- is View -> context
- is ActivityViewManager -> activity
- else -> TODO()
-}
+
+val ViewManager.context
+ get() =
+ when (this) {
+ is View -> context
+ is ActivityViewManager -> activity
+ else -> TODO()
+ }
fun <VM : ViewManager, V : View> VM.add(construct: (Context) -> V, init: V.() -> Unit) {
construct(context).apply(init).also {
diff --git a/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/PipActivity.kt b/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/PipActivity.kt
index d162c43..37566b4 100644
--- a/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/PipActivity.kt
+++ b/activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/PipActivity.kt
@@ -44,9 +44,7 @@
textView = findViewById(R.id.textView)
moveToRandomPosition()
- moveButton.setOnClickListener {
- moveToRandomPosition()
- }
+ moveButton.setOnClickListener { moveToRandomPosition() }
trackHintView()
}
@@ -61,19 +59,18 @@
private fun trackHintView() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- trackPipAnimationHintView(moveButton)
- }
+ repeatOnLifecycle(Lifecycle.State.STARTED) { trackPipAnimationHintView(moveButton) }
}
}
}
private fun moveToRandomPosition() {
- moveButton.layoutParams = RelativeLayout.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
- ).apply {
- randomPosition().forEach { rule -> addRule(rule) }
- }
+ moveButton.layoutParams =
+ RelativeLayout.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT
+ )
+ .apply { randomPosition().forEach { rule -> addRule(rule) } }
}
private fun randomPosition(): List<Int> {
diff --git a/gradle.properties b/gradle.properties
index 84e89af..6d5916f 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -48,7 +48,7 @@
androidx.unpinComposeCompiler=false
# Prefix of projects that are opted-in to use ktfmt
-androidx.ktfmt.optin=:annotation,:appcompat,:buildSrc
+androidx.ktfmt.optin=:activity,:annotation,:appcompat,:buildSrc
# Disable features we do not use
android.defaults.buildfeatures.aidl=false