How to prevent to navigate to the previous page

Shay Wilner 1,746 Reputation points
2023-08-30T19:34:37.52+00:00

Hello

In android app xamarin

In my app i have 2 activities.

Is there a possibility to prevent the user to navigate to the previous activity (the last page).

when i click the > on the bottom toolbar i navigate to the last page so i would like to prevent

the user

Thanks

Developer technologies .NET Xamarin
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2023-09-01T03:11:07.7033333+00:00

    Hello,

    For preventing the back key from returning, in Android you can achieve this by rewriting OnBackPressed.

    Please refer to the key snippets below:

    For activity1:

    Intent intent = new Intent(this, typeof(Activity1));
    // Declare that this navigation stack currently has two activities when the page jumps
    intent.PutExtra("stack_count", 1);
    StartActivity(intent);
    

    For Activity2:

    // If this activity is second, the back event is not triggered.
    public override void OnBackPressed()
    {
        int count = Intent.GetIntExtra("stack_count", 0);
        if (count < 1)
        {
            base.OnBackPressed();
        }
    }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Graham McKechnie 441 Reputation points
    2023-09-03T22:52:45.69+00:00

    How do you claim that is the correct answer when OnBackPressed is now deprecated?

    0 comments No comments

  2. Graham McKechnie 441 Reputation points
    2023-09-04T00:13:12.0233333+00:00

    Further to my earlier comment about OnBackPressed being deprecated.

    A couple of examples showing how to replace it.

    https://vladislavantonyuk.github.io/articles/Migrate-the-deprecated-OnBackPressed-function-in-.NET-MAUI-Android-application/

    The above is for Maui users.

    The next is for Android either Xamarin.Android or Net7. The example is a Net7 project but the logic can just as easily be backported to a Xamarin.Android project.

    https://github.com/gmck/PredictiveBackGestureNet7

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.