Is there a method like Android's Finish() in Xamarin Forms? - c#

I am looking for a method that will end the previous pages/activities as I navigate through different pages so that when the back button is pressed it does not navigate back to that previous message. In Java Android such a method is called finish(), so is there such a method in Xamarin Cross Platform?

Xamarin Forms has some options to remove from or add pages to the stack. Take a look at Navigation.PopAsync or Navigation.RemovePage.

On Xamarin Form for Android, you have a similar method for that: Finish();
I think you are finding this method?

There's no method finish in xamarin forms because finish() is to let the system know that the programmer wants the current Activity to be finished. In xamarin forms you only have one Activity which is MainActivity. Xamarin forms revolves around Navigation, So if you want to go back to previous navigation Navigation.PopAsync or if you want to close a modal use Navigation.PopModal

Based on how you described your objective, I think this.Finish(); will work like a charm.
Example Code:
Button nextPage;
protected override void OnCreate(Bundle savedInstanceState)
{
try
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.your_content_xml);
// Set our view from the "main" layout resource
nextPage = FindViewById<Button>(Resource.Id.button1);
nextPage.Click += (s, e) =>
{
Intent nextActivity = new Intent(this, typeof(next_page_CS_file)); // Create Intent instance
StartActivity(nextActivity); // Go to the Next Page as set in Intent
this.Finish(); // Terminates Current Page.
// As such, once you're in the next page, clicking the back button
// on phone's menu will close the App instead of going back here
};
} catch (Exception ex)
{
// Any code you want that'll handle the Exception.
// Like, for example, . . .
Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show();
}
}
From my understanding and experience, this should work. However I'm unsure if there are other ways of accomplishing what you aim for.

Related

Why does OnAppearing not fire every time in Android

I have a Xamarin project. When I run in UWP OnAppearing initially fires once and then loads the Login Page. After successfully logging in, my Main page fires OnAppearing again and I load data into my ViewModel.
However, if I run the project in Android, OnAppearing only fires once - When the Main page initially loads.
protected override async void OnAppearing()
{
if (!App.IsUserLoggedIn)
{
await App.NavigationService.NavigateModalAsync(PageNames.LoginPage, false);
}
else
{
((SchedulerViewModel)Schedule.BindingContext).LoadData();
}
base.OnAppearing();
}
Why does Android only fire once? Or is UWP the one misbehaving?
NOTE: NavigationService is not a standard Xamarin Forms class. I assume it is built on top of Page.Navigation.PushModalAsync and PopModalAsync.
This is documented behavior of Modal Stack on Android:
Popping Pages from the Modal Stack:
When PopModalAsync is invoked, the following events occur:
...
The page being returned to has its OnAppearing override invoked, provided that the underlying platform isn't Android.
NOTE: it seems to depend on the API version of Android. I just tested it on API 30, and Android did fire OnAppearing again, when modal page was popped.
Instead of code in OnAppearing, I would solve it like this:
In App.xaml.cs, instead of:
MainPage = new MainPage();
do:
if (!App.IsUserLoggedIn)
MainPage = new LoginPage();
else
MainPage = new MainPage();
Then when LoginPage is done, instead of pop modal, do:
Application.Current.MainPage = new MainPage();
NOTE: Adapt as needed, if these are pages inside NavigationPage or AppShell.

Xamarin Forms: How to show a full screen page when selecting a specific tab

I have a tabbed main application with Xamarin Forms.
I am looking to open a Content page in full screen (without tabs and titles) when switching to a specific tab.
I am able to obtain the desired behaviour when I press a button like this:
await Navigation.PushModalAsync(new DashboardPage());
Though i'm not sure how to make it to automatically open when switching to that specific tab.
Any help will be so much appreciated,
Thanks!
I managed to obtain it by adding the following to the tab page class:
protected override void OnAppearing()
{
base.OnAppearing();
Navigation.PushModalAsync(new DashboardPage());
}
protected override void OnDisappearing()
{
base.OnDisappearing();
// move on a different tab to avoid infinite loop when back button is pressed
var masterPage = this.Parent as TabbedPage;
masterPage.CurrentPage = masterPage.Children[0];
}
Probably not the most elegant way but it does the job

How to open a specific view of a uwp application with a secondary tile?

i currently implement an uwp application and i would like to use a secondary tile. I succeeded to create this tile but i don't find any documentation explaining how to open the view of my application when i click on this tile. Thanks in advance for your help.
I find a solution to this problem. In fact, i use the same strategy as windows 8.
We just need to use the OnLaunched event handler (in App.Xaml.cs) to discover if the app is launched from a SecondaryTile or the primary one
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
bool CalledFromSecondaryTile = false;
if (!string.IsNullOrEmpty(e.Arguments))
{
CalledFromSecondaryTile = true;
}

Override BackKeyPress in a classlibrary, is that possible on WP8?

I pass a PhoneApplicationPage instance to a classlibrary, and popup an usercontrol in this classlibrary, when I press back button, the whole application exit. Yesterday I sovled the problem in an application, but I cannot use the method in this classlibrary case.
I tried to subscribe to the event(BackKeyPress), but VS2012 says "parent_BackKeyPress" "System.EventHandler" override and delegate cannot match. I checked, they match.
PhoneApplicationPage mContext=...;
mContext.BackKeyPress += new EventHandler(parent_BackKeyPress);
void parent_BackKeyPress(CancelEventArgs e)
{
ppChangePIN.IsOpen = false;
Application.Current.RootVisual.Visibility = Visibility.Visible;
}
anything incorrect here? plus, can I use navigationservice in classlibrary? I did this before to navigate to a page created in the classlibrary like below, well it ends up crashing. Some say can't use pages in classlibrary, instead we should use Popup(usercontrol).
mContext.NavigationService.Navigate(new Uri("/ChangePINPage.xaml", UriKind.Relative));
I have successfully done just that:
// or some other method of accessing the current page
// - but via Application, to which you have access also in class library
var currentPage = (PhoneApplicationPage)((PhoneApplicationFrame)Application.Current.RootVisual).Content;
currentPage.BackKeyPress += (sender, args) =>
{
// Display dialog or something, and when you decide not to perform back navigation:
args.Cancel = true;
};
Of course you have to make sure that this code is executed if and only if the CurrentPage is the main page.
I also use Pages in class library. You can use NavigationService in class library: you can get it for example from current page obtained as above (currentPage.NavigationService). Or you could use the Navigate method of PhoneApplicationFrame:
((PhoneApplicationFrame)Application.Current.RootVisual)
.Navigate(
new Uri(
"/ClassLibraryName;component/SamplePage.xaml",
UriKind.Relative));
As the short Uris like "/SamplePage.xaml" will work in Application Project, to navigate to page in class library you have to give full location: "/ClassLibraryName;component/SamplePage.xaml".
But note, that if the application chooses to display message box to stop from exiting, it will not pass certification, as (from Technical certification requirements for Windows Phone):
5.2.4.2 – Back button: first screen
Pressing the Back button from the first screen of an app must close the app.

Kill an app when return from WebBrowseTask

I made a small app, and I have a button than pin to start a web blog via a xaml, so when the tile is pin, it goes to the xaml, which automatically redirect to the blog by WebBrowserTask. MY problem is that if they press the back button from the web page, they go to the xaml, and I want them to go directly to the start menu, so I'm looking for a way to kill the app when they return from the
the xaml code is
private void WebPages_Loaded(object sender, RoutedEventArgs e)
{
try
{
WebBrowserTask task = new WebBrowserTask();
task.Uri = new Uri(NavigationContext.QueryString["uri"]);
task.Show();
}
catch (KeyNotFoundException)
{
MessageBox.Show("No URI was passed to the app.");
}
}
I don't know if this is possible, but if someone knows i'll be pleased. Thanks
Try this : Windows Phone 7 close application to kill an app, you may want to try this solution :
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
You may want to load your blog inside a WebBrowser control rather than running a WebBrowseTask. Then, clear the back stack if need be in the OnBackKeyPress event. If you open a WebBrowserTask, the user will have to hit back to resume your app and then hit back again to return to the start menu. You won't be able to exit your app automatically after resuming. Its against the marketplace guidelines.

Categories