Xamarin.Forms MvvM Prism Software and Hardware Back Button - xamarin.forms

I have problem with implementation Code which resolve problem with confirm software nad hardware button back. I need confirm and save state page field. When confirm is true and save state have no error I want close page and when confirm is false or save state have error I want stop closing page. I use xamarin.forms with mvvm prism.

If you mean want to custom the method of Software and Hardware Back Button of Android device, you could override OnOptionsItemSelected and OnKeyDown method in MainActivity.cs to achieve that.
Software Back Button code in MainActivity.cs:
protected override void OnCreate(Bundle savedInstanceState)
{
...
Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
SupportActionBar.SetHomeButtonEnabled(true);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
if(item.ItemId == Android.Resource.Id.Home)
{
Console.WriteLine("software back button press");
return false;
}
else
{
return base.OnOptionsItemSelected(item);
}
}
Hardware Back Button code in MainActivity.cs:
public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
if(e.Action == KeyEventActions.Down && keyCode == Keycode.Back)
{
Console.WriteLine("hardware back button press");
}
return false;
}

Related

How to detect when a fire tv application is minimized?

Is there a way to detect when a user minimizes the fire tv application by pressing the home icon on the remote?
No there is no key event to detect the Home button key press but u can
check for onStop method of the activity and where u can add additional
condition whether backkey pressed or not as its always called before
onStop().
boolean flag=false;
#Override
public void onBackPressed() {
super.onBackPressed();
flag=true;
}
#Override
protected void onStop() {
super.onStop();
if(flag){
//back button pressed
}
else{
// Home button pressed
}
}

Handling Keyboard Input at the Page Level with Xamarin Forms

I am working on a Xamarin Forms project for which one requirement is to recognize certain key presses to trigger hot key actions. The devices that we will be deploying the application to have physical keyboards attached. For now, Android is the only platform that is being targeted.
From some research that I did yesterday afternoon, it sounds as though a custom page renderer is what is required. As I played with this concept this morning, I stumbled upon the On* key methods of the Activity class.
I tried adding the following to the MainActivity class in the Android project:
public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
return base.OnKeyUp(keyCode, e);
}
Placing a breakpoint on this method seems to show that this code is what is needed (read, this method is fired whenever I press a key on the keyboard).
The issue is that this method is also fired when an Entry control on the page has focus. Shouldn't the key press be handled by the Entry control and not bubbled up to the page?
Generally speaking, is this the right approach for what I am trying to accomplish? Are there other approaches that someone can point me to that might work better?
When I was working with hardware devices, I had to do something similar. I created a custom renderer for an entry on the Xamarin.android side. This captures the Enter key press for both hard and soft key in different events. I think creating custom render for a page like you did could work too but this only captures key presses for elements that are in focus. This works for me as I have the entry in focus when user presses the hardware Enter key.
[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace Project.Droid.Controls {
public class CustomEntryRenderer : EntryRenderer {
public CustomEntryRenderer(Context context) : base(context) {
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) {
base.OnElementChanged(e);
Control.EditorAction += Control_EditorAction;
Control.KeyPress += NativeEditText_KeyPress;
}
// Fires only for Soft Keyboard
private void Control_EditorAction(object sender, Android.Widget.TextView.EditorActionEventArgs e) {
if (e.ActionId == ImeAction.Done) {
// your code
e.Handled = true;
}
}
// Fires for Hard Keyboard
private void NativeEditText_KeyPress(object sender, KeyEventArgs e) {
if (e.KeyCode == Keycode.Enter && e.Event.Action == KeyEventActions.Up) {
// your code
e.Handled = true;
}
else
e.Handled = false;
}
}
}
FYI: I also tried the MainActivity event that you are using and it did not work for me. I cannot recall why.

Get toolbar in Xamarin.Forms if the first page is not a navigation page

I tried to intercept the software back button in Android. I follow several samples that adds these:`
protected override void OnPostCreate(Bundle savedInstanceState)
{
var toolBar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolBar);
base.OnPostCreate(savedInstanceState);
}
protected override void OnResume()
{
Android.Support.V7.Widget.Toolbar toolbar = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
if (toolbar != null)
SetSupportActionBar(toolbar);
base.OnResume();
}
Then use the OnOptionItemSelected to get the software back button event.
But this didn't work because, for me the first page of the app is login page that does not belong to NavigationPage. After the successful login, I change the Application.Current.MainPage to the root application page that is a NavigationPage. But it is too late, the OnPostCreate or OnResume already been called and the FindViewById(Resource.Id.toolbar) return null.
Any suggestion?
I dont understand whether you are asking xamarin.forms or xamarin.android.
For xamarin.forms
You can navigate from Login Page to Mainpage like this
Navigation.InsertPageBefore(new MainPage(), this);
Navigation.PopAsync();
And In your App.xaml.cs
MainPage = new NavigationPage(new Login());

How to Handle Back Button in Persistent Search Library

In my App i am Using Navigation Drawer and Persistent Search Library in Action
bar https://github.com/KieronQuinn/PersistentSearch
So when i am in my Home Activity and Search View is not Shown and i press back Button
App is Exit Normally (No Issue)
But when Search View is Open and i Press back button there is an Exception Occurs
So i want to know how to handle Back Button In Persistent Search Library
Here is the Exception Details
Exception image
I figure out the way of handling this as
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (this.search.isActivated()) {
closeSearch();
}
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
But Same Exception Occures
Any help will be Appreciated
Put this code in your activity to handle backpress event for search view
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getKeyCode() == 4 && binding.appBrLt.searchbox.getVisibility() == View.VISIBLE) {
//here write the code
return true;
} else {
return super.dispatchKeyEvent(e);
}
}

Save & Restore Page in Xamarin Forms

I'm looking to save the current navigation stack on the OnSleep Event in my Xamarin Forms page and restore it on the OnResume Event. Is it possible to do this?
Cheers!
I think you should not memorize all navigation stack. Your device decide to kill your app or to restart from the last page you have seen when it comes up from background. I think you can memorize if you are "Logged in" or not: if you are "Logged in" you can restart from the first page "after the login", otherwise start "from the login".
For this case you can take a look to this link and use Properties
public class App : Xamarin.Forms.Application
{
public App ()
{
}
protected override void OnStart()
{
// Handle when your app starts
Debug.WriteLine ("OnStart");
checkLogin();
}
protected override void OnSleep()
{
// Handle when your app sleeps
Debug.WriteLine ("OnSleep");
}
protected override void OnResume()
{
// Handle when your app resumes
Debug.WriteLine ("OnResume");
checkLogin();
}
}
void checkLogin(){
if (Application.Current.Properties.ContainsKey("IsLogged"))
{
var IsLogged = Application.Current.Properties ["IsLogged"] as bool;
// do something with IsLogged
if(IsLogged)
MainPage = new MyFirstPage();
else
MainPage = new MyLoginPage();
}
else
MainPage = new MyLoginPage();
}
then, when you have logged in
Application.Current.Properties ["IsLogged"] = true;

Resources