recognize back-button on dialog-service - android

I'm using the Prism- dialog-service to show a dialog with a yes- and a no-button. This works fine. The user makes the choice and the calling page gets the dialogresult.
But it is also possible for the user to press the back-button if the dialog is present and the dialog disappears without any result to the calling page.
I know that I can override the OnBackButtonPressed-event in the MainActivity but this affects everywhere in my app.
It's important for me, that I can handle this behavior (suspend Back-Button or not) individually for each Dialog.
Therefore I'm looking for an event which will be fired if the back-button is pressed while the dialog is shown.
Similary with the OnBackButtonPressed-Event on a ContentPage.

forms project - pages:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
.
.
IsBusy="{Binding IsBusy}">
android project - MainActivity:
public override void OnBackPressed()
{
var allNotBusy = true;
foreach (var fragment in this.GetFragmentManager().Fragments)
{
var contentPage = fragment.GetType().GetProperty("Page")?.GetValue(fragment) as ContentPage;
if (contentPage.IsBusy)
{
allNotBusy = false;
}
}
if (allNotBusy)
{
base.OnBackPressed();
}
}

Related

How to add a page to navigation history to prevent app from exiting?

I'm still rather new to Ionic 4. I'm making an App that receives push notification. The navigation inside the app works like this:
Home page -> Detail page
Every time the user taps on the notification, the app will open and navigates to Detail page. The navigation works but since the navigation history is empty, if the user taps on the hardware back button, the app exits. I want it to redirect the user to Home page instead.
How do I achieve this in Ionic 4? is there any way to push a page to navigation history? I have read the documentation but couldn't find anything about this. The closest was probably NavCtrl.push() but it's no longer usable in Ionic 4.
Thank you.
There may be an easier way to do this but the following approach is a very flexible one because it'd allow you to run any custom logic when the user wants to go back from the page shown after a push notification or a deep link is opened.
Please take a look at this StackBlitz demo.
Please notice that in the demo, I'm redirecting to the DetailsPage as soon as the app is loaded because of the following code from the app-routing.module file:
{
path: "",
redirectTo: "/details/1?fromDeepLink=true", // <-- here!
pathMatch: "full"
}
Anyway, the important part happens in the DetailsPage. There, you need to handle what happens when the user tries to go back using a) the back button from the header and b) the physical back button from Android devices
The code is pretty self-explanatory, but basically in that page I'm looking for the fromDeepLink query string param, and if it's true, the app will register a custom action for both the back button from the header and for the physical back button from Android devices.
The custom action sets the HomePage as the root page, but sets the animationDirection parameter to be 'back'. That way it'd look like the user is going back to that page even if we're actually adding it to the navigation stack.
It's important to notice that this custom handler is being removed as soon as the user leaves the page so that we don't affect the default behaviour of the back button in any other pages.
import { Component, OnInit, ViewChild } from "#angular/core";
import { ActivatedRoute } from "#angular/router";
import { IonBackButtonDelegate, NavController, Platform, ViewDidEnter, ViewWillLeave } from "#ionic/angular";
import { Subscription } from "rxjs";
#Component({
selector: "app-details",
templateUrl: "./details.page.html",
styleUrls: ["./details.page.scss"]
})
export class DetailsPage implements OnInit, ViewDidEnter, ViewWillLeave {
#ViewChild(IonBackButtonDelegate, { static: false })
public backButton: IonBackButtonDelegate;
public itemId: number;
public fromDeepLink: boolean = false;
private unregisterBackButtonAction: Subscription;
constructor(
private platform: Platform,
private route: ActivatedRoute,
private navCtrl: NavController,
) {}
ngOnInit() {
const itemIdParam = this.route.snapshot.paramMap.get("itemId");
const fromDeepLinkParam = this.route.snapshot.queryParamMap.get('fromDeepLink');
this.itemId = +itemIdParam;
this.fromDeepLink = fromDeepLinkParam
? fromDeepLinkParam.toLocaleLowerCase() === 'true'
: false;
}
ionViewDidEnter() {
if(this.fromDeepLink) {
this.initializeCustomBackButtonAction()
}
}
ionViewWillLeave() {
if(this.fromDeepLink) {
this.removeCustomBackButtonAction();
}
}
private initializeCustomBackButtonAction(): void {
const leavingCallback = () => {
console.log('Using custom back button action');
this.navCtrl.navigateRoot('/home', { animationDirection: 'back' });
};
// Override the back button from the header
if (this.backButton) {
this.backButton.onClick = leavingCallback;
}
// Override the physical back button from Android devices
this.unregisterBackButtonAction = this.platform.backButton.subscribeWithPriority(10, leavingCallback);
}
private removeCustomBackButtonAction(): void {
this.unregisterBackButtonAction?.unsubscribe();
}
}
Please also notice that by default the ion-back-button is not shown if there's no page before the current page in the navigation stack, so in the demo I'm setting the defaultHref property like this:
<ion-back-button defaultHref></ion-back-button>
I'm leaving it empty because the component is actually going to override what this back button does with my custom back button action. But the defaultHref needs to be added to the template, otherwise the back button won't be shown.

Pop to root on tabclick FreshTabbedNavigationContainer on android

Consider a tabbar with "home" and "profile" buttons, when i click on either i switch between two pages, on the "home" page the user can navigate multiple times up in the navigationstack still having the focus on the "home" tab indicating that this is where the user came from.
Now, on iOS whenever the user clicks on "home" from high up in the navigationstack the user is popped to root and all is well, this is not the case on android however, on android the user has to pop one page at a time by clicking on the backbutton to get to the root.
Is this intended behavior, am i doing something wrong, does someone have a clue as to what i can do to get the desired behavior?
This is the intended behavior between iOS and Android .
If you need to make the Android has the same effect with iOS, you need to custom TabbedPageRenderer to achieve that. And the bottom tab bar effect can custom a FreshTabbedNavigationContainer . Last, we will use MessagingCenter to send message to Forms to pop to Root Page.
For example, CustomFreshTabbedNavigationContainer class:
public class CustomFreshTabbedNavigationContainer : FreshTabbedNavigationContainer
{
public CustomFreshTabbedNavigationContainer()
{
On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
MessagingCenter.Subscribe<object>(this, "Hi", (sender) =>
{
// Do something whenever the "Hi" message is received
PopToRoot(true);
});
}
}
Used in App.xaml.cs:
public App()
{
InitializeComponent();
var container = new CustomFreshTabbedNavigationContainer();
container.AddTab<FirstPageModel>("Home", default);
container.AddTab<ProfilePageModel>("Profile", default);
MainPage = container;
}
Now we will create a CustomTabbedPageRenderer in Android:
public class CustomTabbedPageRenderer : TabbedPageRenderer, BottomNavigationView.IOnNavigationItemSelectedListener
{
public CustomTabbedPageRenderer(Context context) : base(context)
{
}
int previousItemId = 0;
bool BottomNavigationView.IOnNavigationItemSelectedListener.OnNavigationItemSelected(IMenuItem item)
{
base.OnNavigationItemSelected(item);
if (item.IsChecked)
{
if (previousItemId != item.ItemId)
{
previousItemId = item.ItemId;
}
else
{
Console.WriteLine("ok");
MessagingCenter.Send<object>(this, "Hi");
}
}
return true;
}
}
The effect:
Note: If need to have the same effect with the top Tabbar in Android, there is different code in CustomTabbedPageRenderer. You can have a look at this discussion.

Xamarin Forms pressing back does nothing when the keyboard is hidden

I am writing a Xamarin Forms app (.net standard 2.0). Currently it is only being developed for Android but it may be released for other OSs in future. The scenario I am trying to manage is this:
The user goes into a ContentPage with a single Entry
I give the Entry focus by using native Android code in a custom renderer:
if (e.NewElement != null && e.NewElement is CustomEntry)
{
CustomEntry customEntry = (CustomEntry)e.NewElement;
if(customEntry.GiveFocus)
{
//this messes up the onback behaviour - you have to press onback twice to exit the screen, once to get out of the hidden SIP
Control.RequestFocus();
}
}
I do not want the soft keyboard to pop up automatically. Therefore I have added the below line to the OnCreate of the MainActivity:
Window.SetSoftInputMode(SoftInput.StateAlwaysHidden);
The reason I am requesting focus in the custom renderer and not in the Xamarin Forms Entry is I could see the keyboard popup and then immediately disappear when I requested it in the Xamarin Forms control. I don't want the keyboard to appear as this app will be primarily used by users of industrial devices with a hardware keyboard, but the entry will need to have focus as the users will want to enter text into it straight away.
My problem is the user has to press the back button twice to exit the ContentPage in this scenario. Once to get out of the hidden keyboard (and the Entry loses focus) and then again to exit the page. I want to avoid this - they should be able to exit the page with only one click when the keyboard is hidden. Does anyone know how to resolve this? I have tried overriding OnKeyPreIme in the custom renderer as other answers have suggested but it doesn't appear to detect the back click.
You can use Hide Keyboard method when your entry get focused. It might solved your problem.
public interface IKeyboardHelper
{
void HideKeyboard();
}
For Android use :
public class DroidKeyboardHelper : IKeyboardHelper
{
public void HideKeyboard()
{
var context = Forms.Context;
var inputMethodManager = context.GetSystemService(Context.InputMethodService) as InputMethodManager;
if (inputMethodManager != null && context is Activity)
{
var activity = context as Activity;
var token = activity.CurrentFocus?.WindowToken;
inputMethodManager.HideSoftInputFromWindow(token, HideSoftInputFlags.None);
activity.Window.DecorView.ClearFocus();
}
}
}
For iOS :
public class iOSKeyboardHelper : IKeyboardHelper
{
public void HideKeyboard()
{
UIApplication.SharedApplication.KeyWindow.EndEditing(true);
}
}
Use Dependency Injection and call this method while your entry get focused.
Try to use below method for handling back button pressed event.
protected override bool OnBackButtonPressed()
{
// you can handle back button pressed event in Xamarin forms page
return base.OnBackButtonPressed();
}
I've (finally) worked it out. The key is not to override OnKeyPreIME but DispatchKeyEventPreIme instead. This allows you to intercept the 'Back' press. So, in my CustomRenderer I added this method:
public override bool DispatchKeyEventPreIme(KeyEvent e)
{
//if this is back press and the sip is not visible then we need to call the 'OnBack' method at the view model level
if(!SIPVisibleListener.IsSIPVisible && e.KeyCode == Keycode.Back)
{
if(XamarinFormsControl != null && XamarinFormsControl is IOnBackHandler)
{
((IOnBackHandler)XamarinFormsControl).GoBack();
}
}
return base.DispatchKeyEventPreIme(e);
}
IOnBackHandler is an interface I created to handle the back key press. SIPVisibleListener is based on an answer to this question: How do I Detect if Software Keyboard is Visible on Android Device?
Hopefully this will help someone.

How to identify back button event in Xamarin cross-platform (Xamarin.Forms)

Is there any way to know when the 'back' button event on the 'Android phone' is pressed? I'd like to exit the game and add few functionality to it when this button is pressed in Xamarin.Forms.
I googled a bit regarding this, but I got articles regarding Xamarin.Android Back button but not for Xamarin.Forms.
As I am relatively new to Xamarin.Forms, please help me out
public override void OnBackPressed()
{
//base.OnBackPressed();
}
Same thing I want in Xamarin.Forms. Need some assistance, guys.
If you mean Xamarin.Forms by "Xamarin Cross Platform", there is a OnBackButtonPressed event that you can use. As seen on that documentation:
Event that is raised when the hardware back button is pressed. This
event is not raised on iOS.
Simply override this event on your NavigationPage and you're ready to go:
protected override bool OnBackButtonPressed()
{
// Do your magic here
return true;
}
Good luck!
In my xamarin forms app you need to find the NavigationStack of the current Page if you are using master page:
public bool DoBack
{
get
{
MasterDetailPage mainPage = App.Current.MainPage as MasterDetailPage;
if (mainPage != null)
{
bool doBack = mainPage.Detail.Navigation.NavigationStack.Count > 1 || mainPage.IsPresented;
//top level of page and the Master menu isn't showing
if (!doBack)
{
// don't exit the app only show the Master menu page
mainPage.IsPresented = true;
return false;
}
else
{
return true;
}
}
return true;
}
}

Back button behavior within an InAppBrowser window with Cordova 3.6?

I'm writing a mobile application using cordova 3.6, this app just open an external url corresponding to the mobile version of my website
var ref = window.open('http://www.stackoverflow.com', '_self', 'location=no');
If a use _self as the target, the back button behavior is fine forme as it works correctly within browesed pages but the problem is that the last back in the history stack done go back on my index page and then open once again my url ! Also the events on the window doesn't work. How to exit?
var ref = window.open('http://www.stackoverflow.com', '_blank', 'location=no');
If a use _self as the target, the back button behavior is not the same. There is no back possible within browsed pages, just a back on the index page whatever we are. How can I modify the behavior to have the same as the _self?
I am stuck with these 2 solutions :(
Note: I saw this similar question but the suggested code
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
closeDialog();
}
});
no more exists in cordova InAppBrowser.java no more exist
I found a working solution for the "_blank" option target using cordova 3.6 thanks to the answer of Kris Erikson on this post
With those modifications the hardware back button works within pages in an InAppBrowser.
I copy hereafter his working solution
Go to src/com/org/apache/corodova/inappbrowser directory and edit the InAppBrowserDialog.java:
Change
public void onBackPressed () {
if (this.inAppBrowser == null) {
this.dismiss();
} else {
// better to go through the in inAppBrowser
// because it does a clean up
this.inAppBrowser.closeDialog();
}
}
to
public void onBackPressed () {
if (this.inAppBrowser == null) {
this.dismiss();
} else {
if (this.inAppBrowser.canGoBack()) {
this.inAppBrowser.goBack();
} else {
this.inAppBrowser.closeDialog();
}
}
}
Then go to InAppBrowser and find the goBack function, change:
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
private void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
to
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
Please post if you find a better solution avoiding to modify the java code

Categories

Resources