Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix fragment lifecycle #53

Merged
merged 1 commit into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .idea/inspectionProfiles/ktlint.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion framework/ui/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ android {
includeAndroidResources = true
}
animationsDisabled true
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
packagingOptions {
resources {
Expand Down Expand Up @@ -110,5 +109,10 @@ dependencies {
implementation libs.compose.material.iconsext

androidTestImplementation libs.androidx.test.runner
androidTestImplementation libs.androidx.test.core.ktx
androidTestImplementation libs.androidx.test.junit
androidTestImplementation libs.androidx.test.espresso.core
androidTestImplementation libs.truth
androidTestImplementation libs.compose.ui.test.junit4
testImplementation libs.androidx.test.runner
}
31 changes: 31 additions & 0 deletions framework/ui/src/androidTest/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?><!--
~ Copyright 2023 Google LLC
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ https://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.catalog.framework.ui.test">

<application>
<activity
android:name="com.google.android.catalog.framework.ui.TestActivity"
android:exported="true"
android:theme="@style/Theme.Material3.DayNight.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.catalog.framework.ui

import com.google.android.catalog.framework.base.CatalogSample
import com.google.android.catalog.framework.base.CatalogTarget
import com.google.android.catalog.framework.ui.components.LifecycleFragment

class TestActivity : CatalogActivity() {

init {
catalogSamples = setOf(
CatalogSample(
name = "LifecycleFragment",
description = "description",
tags = emptyList(),
documentation = "documentation",
sourcePath = "sourcePath",
path = "path",
owners = emptyList(),
target = CatalogTarget.TargetFragment(LifecycleFragment::class),
minSDK = 0,
route = "/fragment",
)
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.catalog.framework.ui.components

import android.content.pm.ActivityInfo
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.android.catalog.framework.ui.TestActivity
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@MediumTest
@RunWith(AndroidJUnit4::class)
class FragmentContainerTest {

@get:Rule
val rule = createAndroidComposeRule<TestActivity>()

@Test
fun fragmentLifecycle() {
rule.onNodeWithText("LifecycleFragment").performClick()
rule.waitForIdle()
val fragments = rule.activity.supportFragmentManager.fragments
assertThat(fragments).hasSize(1)
assertThat(fragments[0]).isInstanceOf(LifecycleFragment::class.java)
onView(withText("hello lifecycle")).check(matches(isDisplayed()))
val fragment = fragments[0] as LifecycleFragment
assertThat(fragment.created).isTrue()
assertThat(fragment.started).isTrue()
assertThat(fragment.resumed).isTrue()
pressBack()
rule.waitForIdle()
assertThat(fragment.resumed).isFalse()
assertThat(fragment.started).isFalse()
assertThat(fragment.created).isFalse()
}

@Test
fun orientationChange() {
rule.onNodeWithText("LifecycleFragment").performClick()
rule.waitForIdle()
// Switch to portrait. It's probably portrait right from the start.
rule.activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
rule.waitForIdle()
onView(withText("hello lifecycle")).check(matches(isDisplayed()))
// Switch to landscape.
rule.activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
rule.waitForIdle()
onView(withText("hello lifecycle")).check(matches(isDisplayed()))
// Back to portrait.
rule.activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
rule.waitForIdle()
onView(withText("hello lifecycle")).check(matches(isDisplayed()))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.catalog.framework.ui.components

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment

class LifecycleFragment : Fragment() {

var created = false

var started = false

var resumed = false

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
created = true
}

override fun onStart() {
super.onStart()
started = true
}

override fun onResume() {
super.onResume()
resumed = true
}

override fun onPause() {
resumed = false
super.onPause()
}

override fun onStop() {
started = false
super.onStop()
}

override fun onDestroy() {
created = false
super.onDestroy()
}

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return TextView(inflater.context).apply {
text = "hello lifecycle"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ private fun NavGraphBuilder.addTargets(
FragmentContainer(
modifier = Modifier.fillMaxSize(),
fragmentManager = fragmentManager,
commit = { id ->
add(id, target.targetClass.java.getDeclaredConstructor().newInstance())
}
createFragment = {
target.targetClass.java.getDeclaredConstructor().newInstance()
},
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,9 @@ internal fun CatalogScreen(
FragmentContainer(
modifier = Modifier.fillMaxSize().padding(innerPadding),
fragmentManager = fragmentManager,
commit = { id ->
add(
id,
target.targetClass.java.getDeclaredConstructor().newInstance()
)
}
createFragment = {
target.targetClass.java.getDeclaredConstructor().newInstance()
},
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,34 +17,41 @@
package com.google.android.catalog.framework.ui.components

import android.view.View
import android.view.ViewGroup
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentContainerView
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.fragment.app.commit

@Composable
internal fun FragmentContainer(
modifier: Modifier = Modifier,
fragmentManager: FragmentManager,
commit: FragmentTransaction.(containerId: Int) -> Unit
createFragment: () -> Fragment,
) {
val containerId by rememberSaveable {
mutableStateOf(View.generateViewId())
}
AndroidView(modifier = modifier, factory = { context ->
fragmentManager.findFragmentById(containerId)?.view?.also {
(it.parent as? ViewGroup)?.removeView(
it
)
} ?: FragmentContainerView(context).apply { id = containerId }.also {
fragmentManager.commit { commit(it.id) }
val containerId = remember { View.generateViewId() }
AndroidView(
modifier = modifier,
factory = { context ->
FragmentContainerView(context).also { view ->
view.id = containerId
}
},
)
DisposableEffect(fragmentManager) {
fragmentManager.commit {
replace(containerId, createFragment())
}
onDispose {
fragmentManager.findFragmentById(containerId)?.let { fragment ->
fragmentManager.commit(allowStateLoss = true) {
remove(fragment)
}
}
}
}, update = {})
}
}
5 changes: 5 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ coroutines = "1.7.3"
hilt = "2.48.1"
androidxtest = "1.4.0"
navigation = "2.5.3"
androidxJunit = "1.1.5"
espresso = "3.5.1"

[libraries]
android-gradlePlugin = { module = "com.android.tools.build:gradle", version.ref = "gradlePlugin" }
Expand All @@ -44,6 +46,9 @@ androidx-navigation-fragment = "androidx.navigation:navigation-fragment:2.7.5"
androidx-navigation-compose = "androidx.navigation:navigation-compose:2.7.5"

androidx-test-runner = "androidx.test:runner:1.5.2"
androidx-test-core-ktx = "androidx.test:core-ktx:1.5.0"
androidx-test-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidxJunit" }
androidx-test-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espresso" }

mdc = "com.google.android.material:material:1.10.0"

Expand Down
Loading