How to clear the whole backstack for all nested NavGraphs? - android-jetpack-compose

I have an application with a NavigationBar that includes three destinations. It is configured so that two of the destinations point to a seperate nested NavGraph, namely IssuesGraph and InstructionsGraph. While navigating within the nested graphs and then switching between the two destinations, the respective stack for each nested graph is saved as I wish.
NavigationBar {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
bottomNavigationItems.forEachIndexed { index, item ->
NavigationBarItem(
icon = { Icon(item.imageResource, stringResource(id = item.titleResource)) },
label = { Text(stringResource(id = item.titleResource)) },
selected = currentDestination?.hierarchy?.any { it.route == item.route } == true,
onClick = {
navController.navigate(item.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
// Restore state when reselecting a previously selected item
restoreState = true
}
}
)
}
}
However, I now need to reset the complete navigation graph, so I want the App to display the first destination within the IssuesGraph, and if I navigate to the InstructionsGraph, it should show its first destination, too.
My NavHost looks like this:
NavHost(
modifier = modifier,
navController = navController,
startDestination = startDestination,
) {
issueGraph(navController, issuesVM)
instructionsGraph(navController, instructionsVM)
composable(Screen.SettingsScreen.route) {
SettingsScreen(
onSave = {
// Here, I want to trigger a reset of
// the backstacks of issuesGraph and instructionsGraph
// and navigate to the first screen of the issuesGraph
navController.navigate(Screen.IssuesGraph.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = false
}
}
}
)
}
}
The seperate NavGraphs are built using the NavGraphBuilder extension function:
fun NavGraphBuilder.issueGraph(navController: NavController, issuesVM: IssuesVM) {
navigation(startDestination = Screen.IssuesHome.route, Screen.IssuesGraph.route) {
composable(Screen.IssuesHome.route) {
//...
}
}
}
The problem is, that calls like this
navController.navigate(Screen.IssuesGraph.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = false
}
}
only clear the back stack for the nested NavGraph the the goal route Screen.IssuesGraph.route resides in. So in my case, the IssuesGraph is reset, but the InstructionsGraph isn't. When I navigate there, it still shows its previous backstack.
I already stumbled across the setGraph documentation, but couldn't understand how I could use it in my case.
Thanks for any efforts!

Related

Nested Navigation inside Compose BottomSheet

for my App, I want to use a ModalBottomSheetLayout which is able to have a nested Navigation inside the BottomSheet.
For e.g. the User clicks a Button on the Homescreen and the BottomSheet opens. Inside the BottomSheet is a list of Elements. If one Element is clicked, then the Details Screen should open inside the same BottomSheet. I have tried to find a solution using appcompanist navigation and the BottomSheetNavigator, but unfortunally it doesnt work as expected.
If I run the following Code and click on one ELement, than the BottomSheet with the Element gets closed and a new one for the Detail-Screen will be opened. But I do not want to have this effect of a new BottomSheet, I would like to have a nested navigation inside one BottomSheet.
val modalBottomSheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
skipHalfExpanded = true
)
val bottomSheetNavigator = remember(modalBottomSheetState) {
BottomSheetNavigator(sheetState = modalBottomSheetState)
}
val navHostController = rememberNavController()
ModalBottomSheetLayout(
bottomSheetNavigator = bottomSheetNavigator,
content = {
Scaffold(
bottomBar = {
...
},
content = { innerPadding ->
NavHost(
navController = navHostController,
startDestination = vmMain.getStartDestination(),
modifier = Modifier.padding(innerPadding)
) {
navigation(
startDestination = OnboardingDirections.appPreview().destination,
route = OnboardingDirections.root().destination
) {
composable(OnboardingDirections.appPreview().destination) {
IntroScreen()
}
...
}
bottomSheet(route = FeatureA.root().destination) {
ScreenA()
}
bottomSheet(route = FeatureA.x().destination) {
ScreenB()
}
}
}
)
}
What I would need, is something like this:
bottomSheet(route = FeatureA.root().destination) {
navigation(route = "x") {
ScreenA()
}
navigation(route = "y") {
ScreenB()
}
}

How to stop Surface from passing through clicks [duplicate]

The below code is for Jetbrains Desktop Compose. It shows a card with a button on it, right now if you click the card "clicked card" will be echoed to console. If you click the button it will echo "Clicked button"
However, I'm looking for a way for the card to detect the click on the button. I'd like to do this without changing the button so the button doesn't need to know about the card it's on. I wish to do this so the card knows something on it's surface is handled and for example show a differently colored border..
The desired result is that when you click on the button the log will echo both the "Card clicked" and "Button clicked" lines. I understand why mouseClickable isn't called, button declares the click handled. So I'm expecting that I'd need to use another mouse method than mouseClickable. But I can't for the life of me figure out what I should be using.
#OptIn(ExperimentalComposeUiApi::class, androidx.compose.foundation.ExperimentalDesktopApi::class)
#Composable
fun example() {
Card(
modifier = Modifier
.width(150.dp).height(64.dp)
.mouseClickable { println("Clicked card") }
) {
Column {
Button({ println("Clicked button")}) { Text("Click me") }
}
}
}
When button finds tap event, it marks it as consumed, which prevents other views from receiving it. This is done with consumeDownChange(), you can see detectTapAndPress method where this is done with Button here
To override the default behaviour, you had to reimplement some of gesture tracking. List of changes comparing to system detectTapAndPress:
I use awaitFirstDown(requireUnconsumed = false) instead of default requireUnconsumed = true to make sure we get even a consumed even
I use my own waitForUpOrCancellationInitial instead of waitForUpOrCancellation: here I use awaitPointerEvent(PointerEventPass.Initial) instead of awaitPointerEvent(PointerEventPass.Main), in order to get the event even if an other view will get it.
Remove up.consumeDownChange() to allow the button to process the touch.
Final code:
suspend fun PointerInputScope.detectTapAndPressUnconsumed(
onPress: suspend PressGestureScope.(Offset) -> Unit = NoPressGesture,
onTap: ((Offset) -> Unit)? = null
) {
val pressScope = PressGestureScopeImpl(this)
forEachGesture {
coroutineScope {
pressScope.reset()
awaitPointerEventScope {
val down = awaitFirstDown(requireUnconsumed = false).also { it.consumeDownChange() }
if (onPress !== NoPressGesture) {
launch { pressScope.onPress(down.position) }
}
val up = waitForUpOrCancellationInitial()
if (up == null) {
pressScope.cancel() // tap-up was canceled
} else {
pressScope.release()
onTap?.invoke(up.position)
}
}
}
}
}
suspend fun AwaitPointerEventScope.waitForUpOrCancellationInitial(): PointerInputChange? {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
if (event.changes.fastAll { it.changedToUp() }) {
// All pointers are up
return event.changes[0]
}
if (event.changes.fastAny { it.consumed.downChange || it.isOutOfBounds(size) }) {
return null // Canceled
}
// Check for cancel by position consumption. We can look on the Final pass of the
// existing pointer event because it comes after the Main pass we checked above.
val consumeCheck = awaitPointerEvent(PointerEventPass.Final)
if (consumeCheck.changes.fastAny { it.positionChangeConsumed() }) {
return null
}
}
}
P.S. you need to add implementation("androidx.compose.ui:ui-util:$compose_version") for Android Compose or implementation(compose("org.jetbrains.compose.ui:ui-util")) for Desktop Compose into your build.gradle.kts to use fastAll/fastAny.
Usage:
Card(
modifier = Modifier
.width(150.dp).height(64.dp)
.clickable { }
.pointerInput(Unit) {
detectTapAndPressUnconsumed(onTap = {
println("tap")
})
}
) {
Column {
Button({ println("Clicked button") }) { Text("Click me") }
}
}

Randomly Rearrange items in a LazyRow - Jetpack Compose

I have a LazyRow. Everything works fine. I just want the items to be randomly rearranged every time this LazyRow is drawn on the screen. Here is my code:
LazyRow(
reverseLayout = true,
contentPadding = PaddingValues(top = twelveDp, end = eightDp)
) {
itemsIndexed(
items = featureUsersLazyPagingItems,
key = { _, featuredPerson ->
featuredPerson.uid
}
) { _, featuredUser ->
featuredUser?.let {
//Daw the age suggested People
DrawSuggestedPerson(featuredUser.toPersonUser(),) {
homeViewModel.deleteFeaturedUserFromLocalDb(featuredUser.uid)
}
}
}
featureUsersLazyPagingItems.apply {
when {
loadState.refresh is LoadState.Loading -> {
item {
ShowLazyColumnIsLoadingProgressBar()
}
}
loadState.append is LoadState.Loading -> {
item {
ShowLazyColumnIsLoadingProgressBar()
}
}
loadState.refresh is LoadState.Error -> {
val e = featureUsersLazyPagingItems.loadState.refresh as LoadState.Error
item {
LazyColumnErrorView(
message = e.error.localizedMessage!!,
onClickRetry = { retry() }
)
}
}
loadState.append is LoadState.Error -> {
val e = featureUsersLazyPagingItems.loadState.append as
LoadState.Error
item {
LazyColumnErrorView(
message = e.error.localizedMessage!!,
onClickRetry = { retry() }
)
}
}
}
}
So the LazyRow displays the same set of 30 or so items but only 3- 4 items are visible on screen, for a bit of variety, I would like the items to be re-arranged so that the user can see different items on the screen. Is there a way to achieve this?
You can shuffle your list inside remember, by doing this you're sure that during one view appearance your order will be the same, and it'll be shuffled on the next view appearance. I'm passing featureUsersLazyPagingItems as a key, so if featureUsersLazyPagingItems changes shuffledItems will be recalculated.
val shuffledItems = remember(featureUsersLazyPagingItems) {
featureUsersLazyPagingItems.shuffled()
}
The only problem of remember is that it'll be reset on screen rotation. Not sure if you need that, and if you wanna save state after rotation, you need to use rememberSaveable. As it can only store simple types, which your class isn't, you can store indices instead, like this:
val shuffledItemIndices = rememberSaveable(featureUsersLazyPagingItems) {
featureUsersLazyPagingItems.indices.shuffled()
}
val shuffledItems = remember(featureUsersLazyPagingItems, shuffledItemIndices) {
featureUsersLazyPagingItems.indices
.map(featureUsersLazyPagingItems::get)
}
I suggest you checkout out documentation for details of how state works in compose.

Jetpack Compose: Bottom bar navigation not responding after deep-linking

I have setup a bottom bar in my new Jetpack Compose app with 2 destinations. I have tried to follow the samples from Google.
So for example it looks something like this:
#Composable
fun MyBottomBar(navController: NavHostController) {
val items = listOf(
BottomNavigationScreen.ScreenA,
BottomNavigationScreen.ScreenB
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
BottomNavigation {
items.forEach { screen ->
BottomNavigationItem(
onClick = {
navController.navigate(screen.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
},
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
icon = { Icon(imageVector = screen.icon, contentDescription = null) },
label = { Text(stringResource(screen.label)) }
)
}
}
}
This all works fine and I'm able to navigate between the two destinations. However, I also have a deep-link to ScreenB. Once this has been invoked, pressing the ScreenA button seems to do nothing (If I add logging I can see that currentDestination is being repeatedly set to ScreenB) but pressing back returns to the startDestination of ScreenA.
My workaround at the moment is to remove the restoreState = true line from the sample code.
My suspicion is that something about the deep-link is being persisted and although it tries to go to ScreenA the navigation component says that it's got a deep-link pointing to ScreenB so it just goes there. I've tried resetting the activity intent so that it has no flags and no data in the intent, I've even tried changing the intent action type but all to no avail.
I am using Compose 1.0.0-rc02 and Compose Navigation 2.4.0-alpha04.
Am I doing something wrong or is this a bug?
I know you got this code from the official documentation, but I don't think it works well for bottom navigation. It keeps the elements in the navigation stack, so pressing the back button from ScreenB will take you back to ScreenA, which does not seem to me to be the right behavior in this case.
That's why it's better to remove all elements from the stack, so that only one of the tabs is always left. And with saveState you won't lose state anyway. This can be done as follows:
fun NavHostController.navigateBottomNavigationScreen(screen: BottomNavigationScreen) = navigate(screen.route) {
val navigationRoutes = BottomNavigationScreen.values()
.map(BottomNavigationScreen::route)
val firstBottomBarDestination = backQueue
.firstOrNull { navigationRoutes.contains(it.destination.route) }
?.destination
if (firstBottomBarDestination != null) {
popUpTo(firstBottomBarDestination.id) {
inclusive = true
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
And use it like this:
BottomNavigationItem(
onClick = {
navController.navigateBottomNavigationScreen(screen)
},
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
icon = { Icon(imageVector = screen.icon, contentDescription = null) },
label = { Text(screen.label) }
)
For the same reasons, I wouldn't use deep link navigation in this case. Instead, you process them manually. You can use a view model to not re-process deep link if you leave bottom navigation view and come back:
class DeepLinkProcessingViewModel : ViewModel() {
private var deepLinkProcessed = false
fun processDeepLinkIfAvailable(context: Context): String? {
if (!deepLinkProcessed) {
val activity = context.findActivity()
val intentData = activity?.intent?.data?.toString()
deepLinkProcessed = true
return intentData
}
return null
}
}
And using this view model you can calculate start destination like this:
val context = LocalContext.current
val deepLinkProcessingViewModel = viewModel<DeepLinkProcessingViewModel>()
val startDestination = rememberSaveable(context) {
val deepLink = deepLinkProcessingViewModel.processDeepLinkIfAvailable(context)
if (deepLink == "example://playground") {
// deep link handled
BottomNavigationScreen.ScreenB.route
} else {
// default start destination
BottomNavigationScreen.ScreenA.route
}
}
NavHost(navController = navController, startDestination = startDestination) {
...
}
Or, if you have several navigation elements in front of the bottom navigation and you don't want to lose them with a deep link, you can do it as follows:
val navController = rememberNavController()
val context = LocalContext.current
val deepLinkProcessingViewModel = viewModel<DeepLinkProcessingViewModel>()
LaunchedEffect(Unit) {
val deepLink = deepLinkProcessingViewModel.processDeepLinkIfAvailable(context) ?: return#LaunchedEffect
if (deepLink == "example://playground") {
navController.navigateBottomNavigationScreen(BottomNavigationScreen.ScreenB)
}
}
NavHost(
navController = navController,
startDestination = BottomNavigationScreen.ScreenA.route
) {
findActivity:
fun Context.findActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
Looks like it's finally fixed in the 2.4.0-beta02 release; so it was a bug after all.
I was able to add the saveState and restoreState commands back into my BottomBar (as per the documentation) and following a deep-link I was now still able to click the initial destination.

Hide/Show CircularProgressIndicator onclick Jetpack Compose

I want to show CircularProgressIndicator onclick and then hide !the CircularProgressIndicator when the function is executed see code below
var loader by remember {mutableStateOf(false)}
if(loader){
CircularProgressIndicator()
}
Button (onclick {
loader = !loader // show CircularProgressIndicator
// Function which is to be executed
// After function is executed which usually takes 2 sec then after that CircularProgressIndicator should be hidden
loader = loader // Not hidding
}){
Text("Toggle")
}
Basically you need to check that in any case at the end of your processing firebase = false should be called. I'd advise you at least to move the logic into a separate function, so I'll be harder to make a mistake, but basically it should look something like this:
OutlinedButton(onClick = {
keyboardController?.hide()
if (emailState.value.isEmpty() && secureState.value.isEmpty())
return#OutlinedButton
firebase = true
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
val exception = task.exception?.localizedMessage.toString()
if (task.isSuccessful)
FirebaseAuth.getInstance().currentUser?.sendEmailVerification()
?.addOnCompleteListener { task ->
firebase = true
if (task.isSuccessful)
snackbarCoroutineScope.launch {
scaffoldState.snackbarHostState.showSnackbar(
"Check your Email for Verification")
}
}
else
snackbarCoroutineScope.launch {
scaffoldState.snackbarHostState.showSnackbar(exception)
firebase = true
}
}
}) {
Text(text = "Sign Up")
}
Spacer(modifier = Modifier.size(16.dp))
TextButton(onClick = {
keyboardController?.hide()
if (emailState.value.isEmpty())
return#TextButton
FirebaseAuth.getInstance().sendPasswordResetEmail(email)
.addOnCompleteListener { task ->
val exception = task.exception?.localizedMessage.toString()
firebase = false
if (task.isSuccessful)
snackbarCoroutineScope.launch {
scaffoldState.snackbarHostState.showSnackbar("Check your Email for Password reset")
firebase = true
}
else
snackbarCoroutineScope.launch {
scaffoldState.snackbarHostState.showSnackbar(exception)
firebase = true
}
}
}) {
Text(text = "Forgot password?")
}

Resources