Disabling back button C# Android Xamarin Code Not Responding - c#

So im trying to disable the back button in my app and it seems like the code im using doesnt want to respond, its hard to explain in words so I made a gif so you can see it more clearly and understand because im not sure I will be able to explain in words.
I want to disable the back button in "Activity2" but the codes I've been trying doesnt want to respond to the back button
Ive tried these codes, dont know any more solutions since im new to android development.
First attempt
public override void OnBackPressed ()
{
base.OnBackPressed ();
}
Second attempt (Both did the same thing)
public override void OnBackPressed ()
{
// base.OnBackPressed (); /* Comment this base call to avoid calling Finish() */
// Do nothing
}
What could the possible issue be here?

Try this
protected override bool OnBackButtonPressed()
{
return true;
}
Returning true means that nothing will happen.. if you return false it should still do the default operation (going back)
This is the way to do it on a contentpage atleast... Unsure about activity.
Maybe try this:
OnBackPressed in Xamarin Android
protected override void OnBackPressed()
and
[Activity ( NoHistory = true )]
did you check that pressing the back button actually enters your function?
Set a breakpoint like this :
http://imgur.com/maQCdBg
And start the application in debug mode (F5)

This code will get it to work, make sure you build the program and restart your emulator before you run it (I think thats what made it work for me)
public override void OnBackPressed()
{
// base.OnBackPressed (); /* Comment this base call to avoid calling Finish() */
// Do nothing
}

I did this and it worked perfectly
public override void OnBackPressed()
{
// This prevents a user from being able to hit the back button and leave the login page.
return;
//base.OnBackPressed();
}

Do Just Like This
public override void OnBackPressed()
{
return;
}

You can Try like this
Step 1 Add [Activity(NoHistory =true)
Step 2 Add protected override bool OnBackButtonPressed()
{
return true;
}
to your content page that you want to disable Back Button Pressed.

Related

Unity resets parameter value set with Editor script on play

I've set up a very simple Editor script in Unity 2020.2.1f1 that, upon pressing an Inspector button, should change the value of a specified parameter to a value set in the code.
public override void OnInspectorGUI()
{
DrawDefaultInspector();
StateObject s = (StateObject)target;
if (s.objID == 0)
{
if (GUILayout.Button("Generate Object ID"))
{
GenerateID(s);
}
}
}
public void GenerateID(StateObject s)
{
s.objID = DateTimeOffset.Now.ToUnixTimeSeconds();
}
This all works like it's supposed to. I press the button, the correct number appears in the field, and I'm happy. However, once I switch to Play mode, the value resets to the prefab default and remains that way even when I switch Play mode off.
Am I missing some ApplyChange function or something?
(EDIT: This works, but isn't as good as the accepted answer.)
Well, yes, I am in fact missing some sort of ApplyChange function.
I don't know how I missed it, but I was looking for this:
EditorUtility.SetDirty(target);
So, in my script, I would just edit the GenerateID function:
public void GenerateID(StateObject s)
{
s.objID = DateTimeOffset.Now.ToUnixTimeSeconds();
EditorUtility.SetDirty(s);
}
And I am posting it here in case anyone runs into the same issue, that way they hopefully won't have to spend as much time looking for a solution before being reminded that SetDirty is a thing.
In my eyes better than mixing in direct accesses from Editor scripts and then manually mark things dirty rather go through SerializedProperty and let the Inspector handle it all (also the marking dirty and saving changes, handle undo/redo etc)
SerializedProperty id;
private void OnEnable()
{
id = serializedObject.FindProperty("objID");
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
// Loads the actual values into the serialized properties
// See https://docs.unity3d.com/ScriptReference/SerializedObject.Update.html
serializedObject.Update();
if (id.intValue == 0)
{
if (GUILayout.Button("Generate Object ID"))
{
id.intValue = DateTimeOffset.Now.ToUnixTimeSeconds();
}
}
// Writes back modified properties into the actual class
// Handles all marking dirty, undo/redo, etc
// See https://docs.unity3d.com/ScriptReference/SerializedObject.ApplyModifiedProperties.html
serializedObject.ApplyModifiedProperties();
}

Winforms, control only working with breakpoint

I created a custom Toast Notification for my Winforms application, whenever a custom result is returned, I use a ShowMessage extension to display the notification.
On my login screen, I have a unlock application button that will show the toaster message whenever the password is incorrect.
When I put a breakpoint right before the result.ShowMessage(); the notification appears. But when I remove the breakpoint, it does not appear anymore. I do not change any debug values.
How can I resolve this? I did try implementing a thread.sleep but it did not change anything, the notification only appears when I insert a breakpoint and continue over it.
It is worth noting that the notification works perfectly everywhere else in the application.
Code for the Unlock Application:
private void UnlockApplication()
{
var result = new Business.Server.User().Get(_loginModel.UserName, _loginModel.Password.Encrypt());
if (result.IsSuccessful)
{
// Perform log in process
}
else
{
result.ShowMessage(); //Only works when I put breakpoint here
}
}
Code for ShowMessage extension
public static void ShowMessage<T>(this Models.Result<T> result) where T : class
{
Helpers.ToasterNotificationHelper.ShowNotification(result.ResultTypeKey.ToDescription(), result.Message, result.ResultImage(), result.ResultColor(), result.ResultTypeKey == Enums.ResultTypeEnum.Warning ? 5000 : 2500);
}
public static void ShowNotification(string header, string message, Image icon, Color backgroundColor, int durationInMilliseconds = 1000)
{
if (Application.OpenForms[0] is MyApplication)
{
var toasterNotification = new ToasterNotificationControl(header, message, icon, backgroundColor);
(Application.OpenForms[0] as MyApplication).toastNotificationCollectionControl1.AddNotification(toasterNotification, durationInMilliseconds);
}
}
My Toast Notification control is a DevExpress flyout panel control that gets added to the Main application form
Your "Get(_loginModel.UserName ..." seems to be asynchronous. Try to do the next to make the call awaitable:
private async System.Threading.Tasks.Task UnlockApplicationAsync()
{
var result = await new Business.Server.User().Get(_loginModel.UserName, _loginModel.Password.Encrypt());
...

send data to running async function xamarin

Working with Xamarin Android and C# -
I want to have a download function, that just download the next item (url) from the list if the first with index 0 is finished. While Downloading, the user should be able to extend the list (add new urls for download).
My idea was to have one void OnButtonClick() (for user input) and one custom aysnc void Download() function, as well the possibility to use the "share function" (intent) to send the link directly. It is working BUT only if the user does not uses the "share function" in another app (see here: Intent.GetStringExtra). If the App gets open via this intent, the download loop gets overwritten completely. Is there a way to avoid this "bug" or another solution for a download que?
protected override void OnCreate() //gets called if activity starts
{
string catchedLink = Intent.GetStringExtra(Intent.ExtraText);
if (!String.IsNullOrEmpty(catchedLink))
{
button.Text = catchedLink;
}
}
public OnButtonClick()
{
urlList.Add(Button.Text);
}
private aysnc void Download()
{
if(IsDownloading) return;
IsDownloading = true;
do
{
await DownloadSomethingFromTheInternet(); //Let's say these two function need 2 mins to complete -
await SafeItToStorage(); //But after one minute the user adds a secound url for download
//so this loop needs to run again (see below)
urlList.Remove(urlList[0]);
} while (urlList.Count >= 1) //see here
IsDownloading = false;
}
Please leave a comment if more details are needed.
Okay it's working now:
What I did:
Save the links on the device with Preferences.Set(); not only just with a List
Added LaunchMode = Android.Content.PM.LaunchMode.SingleTask to AndroidMainfest.xml (in <activity [...] />)
Used for intent-input following code:
protected override void OnNewIntent(Intent myIntent)
{
base.OnNewIntent(myIntent);
string catchedLink = myIntent.GetStringExtra(Intent.ExtraText);
if (!String.IsNullOrEmpty(catchedLink))
{
AddVideoToQue(catchedLink);
}
}```
Thanks #Leo Zhu - MSFT for his comments and help!

Loading screen for GoogleMaps activity

I'm trying to implement a loading screen since GoogleMaps sometimes takes ~2 seconds to load. I tried using a RelativeLayout and putting the ImageView above the map fragment and making it ViewStates.Gone once the map loads. However, I noticed that the loading is happening on base.OnCreateBundle and not on SetUpMap() and now I'm clueless how to implement it.
private GoogleMap mMap;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Map);
mSplash = FindViewById<ImageView>(Resource.Id.splash);
SetUpMap();
}
private void SetUpMap()
{
if (mMap == null)
{
FragmentManager.FindFragmentById<MapFragment(Resource.Id.map).GetMapAsync(this);
}
}
public void OnMapReady(GoogleMap googleMap)
{
mSplash.Visibility = ViewStates.Gone;
mMap = googleMap;
mMap.MapType = GoogleMap.MapTypeSatellite;
(...)
}
If I'm not mistaken, OnMapReady is meant to be used to verify that Google Play Services is installed and active on the device. As the documentation puts it:
If Google Play services is not installed on the device, the user will
be prompted to install it, and the onMapReady(GoogleMap) method will
only be triggered when the user has installed it and returned to the
app.
OnMapReady Documentation
Alternatively, the OnMapLoaded function is meant to be called after the map has finished loading its tiles.
Called when the map has finished rendering. This will only be called
once. You must request another callback if you want to be notified
again.
OnMapLoaded Documentation
You can implement the OnMapLoaded function by first setting the callback once you have a reference to the map
mMap.setOnMapLoadedCallback(this);
Finish by simply overriding the OnMapLoaded function and handling it accordingly
#Override
public void onMapLoaded() {
if (mMap != null) {
mSplash.Visibility = ViewStates.Gone;
}
}
Remember that if you need to load the map again and need to display another splash screen, you will first need to set the callback again, as onMapLoaded is only called once per callback.

Managed BHOs not instantiated using Protected Mode

I am writing a BHO for IE using C#. The code I'm concerned with is this:
public class BHO : IObjectWithSite, IOleCommandTarget
{
...
public BHO()
{
MessageBox.Show("Constructor called");
}
public int SetSite(object site)
{
MessageBox.Show("SetSite called!");
if( site != null )
{
_webBrowser = (WebBrowser) site;
_webBrowser.NavigateComplete2 += OnNavigateComplete2;
}
else
{
_webBrowser.NavigateComplete2 -= OnNavigateComplete2;
_webBrowser = null;
}
return 0;
}
private void OnNavigateComplete2(object pDisp, ref object URL)
{
MessageBox.Show("OnNavigateComplete2 called");
}
When IE is run with Protected Mode off, everything works fine. However, if Protected Mode is turned on, NavigateCompleted2() is called, but SetSite() and the constructor are never called (!?!). However, if I create a menu item which calls a method in the BHO class, or open a new tab, everything is correctly called.
Does anyone know why it doesn't work when I open a new IE window?
The full source listing can be found here.
Someone on MSDN answered my question: the constructor and method were still being called, but for some reason the MessageBoxes don't show when I open a new window in Protected Mode until the page is loaded. Variables weren't being set due to a different problem - the constructor was instantiating an object which was silently failing.
I now need help with a different (very much related) problem.

Categories