I have downloaded the sample ToDo List. There are many members in the folder. What member do I click to execute the sample?
Sample ToDo - Downloaded - How do I execute
What is the best way to perform background processing during initial load of a Xamarin.Forms App?
First, I am very new to Xamarin and have like zero experience. Secondly, I have seen several posts that suggest that using a Task.Run(() => { someBackgroundProcessing();}); in the OnStart() method of App.cs is a good way to perform background initializations. I would like to do this, in fact I need to do this so that my app does not appear slow during startup while I load and initialize the data and databases necessary for the app to operate properly.
However after several attempts to make it work I have now decide to grovel for some much need help. When run the code below it all runs great and is exactly what I expect except for one glaring horrible detail - Nothing displays on the MainPage. Sometimes though, it may, but subsequent runs yield nothing, it is very intermittent. I am hoping by posting this that someone may be able to identify where exactly I am going wrong. Is the design flawed? Please help.
To produce this project I used basic Xamarin Forms Android Project template called App2.
****APP2 References/Pkgs***
PackageReference Include="Xamarin.Forms" Version="3.4.0.1009999"
****APP2.ANDROID References/Pkgs***
Reference Include="Mono.Android"
Reference Include="System"
Reference Include="System.Core"
Reference Include="System.Xml.Linq"
Reference Include="System.Xml"
"Xamarin.Forms" Version="3.4.0.1009999"
"Xamarin.Android.Support.Design" Version="28.0.0"
"Xamarin.Android.Support.v7.AppCompat" Version="28.0.0"
"Xamarin.Android.Support.v4" Version="28.0.0"
"Xamarin.Android.Support.v7.CardView" Version="28.0.0"
"Xamarin.Android.Support.v7.MediaRouter" Version="28.0.0"
***** APP2.ANDROID *****
****MainActivity.cs****
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using System;
using System.Threading.Tasks;
namespace App2.Droid
{
[Activity(Label = "App2", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
#region Handle Unhandled Exceptions
/// <summary>
/// Catch Unhandled Exceptions
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
{
}
/// <summary>
/// Catch Unhandled Exceptions
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
}
/// <summary>
/// Catch Unhandled Exceptions
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void CurrentDomain_UnhandledException(
object sender,
UnhandledExceptionEventArgs e)
{
}
#endregion Handle Unhandled Exceptions
}
}
****APP2****
****App.xaml****
<?xml version="1.0" encoding="utf-8" ?>
<StackLayout>
<!-- Place new controls here -->
<Label
HorizontalOptions="Center"
Text="Welcome to Xamarin.Forms! WOOT!!!"
VerticalOptions="CenterAndExpand" />
</StackLayout>
****App.xaml.cs****
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace App2
{
public partial class App : Application
{
BackgroundWorkSubclass backgroundWorker1;
BackgroundWorkSubclass backgroundWorker2;
public App()
{
InitializeComponent();
}
protected override void OnStart()
{
// Handle when your app starts
System.Diagnostics.Debug.WriteLine(string.Format("*****ONSTART - Current Thread is [{0}]", Thread.CurrentThread.ManagedThreadId.ToString()));
//A: This doesn't seem to work - The MainPage loads but never displays.
#region Doesn't seem to work
//Start the worker classes on a background thread so as not to block the UI
Task.Run(() =>
{
System.Diagnostics.Debug.WriteLine(string.Format("*****Background ONSTART - Current Thread is [{0}]", Thread.CurrentThread.ManagedThreadId.ToString()));
backgroundWorker1 = new BackgroundWorkSubclass();
backgroundWorker2 = new BackgroundWorkSubclass();
backgroundWorker1.OnBackgroundWorkStatusChange += BackgroundWorker1_OnBackgroundWorkStatusChange;
backgroundWorker2.OnBackgroundWorkStatusChange += BackgroundWorker2_OnBackgroundWorkStatusChange;
backgroundWorker1.InitializeBackgroundWork();
backgroundWorker2.InitializeBackgroundWork();
});
#endregion Doesn't seem to work
//B: If I comment out A and uncomment B the MainPage
//Seems to load but at the sacrifice of no background init which I need to do
#region Seems to load
//StartMainPage();
#endregion Seems to load
}
private void BackgroundWorker1_OnBackgroundWorkStatusChange(object sender, CustomEventArg args)
{
System.Diagnostics.Debug.WriteLine("********: BackgroundWorker1 Status Change");
}
private void BackgroundWorker2_OnBackgroundWorkStatusChange(object sender, CustomEventArg args)
{
System.Diagnostics.Debug.WriteLine("********: BackgroundWorker2 Status Change");
if (args.Status == BWStatus.Completed)
{
//The work is done we can start the MainPage now.
//Place the call to set the MainPage on the UI thread
Device.BeginInvokeOnMainThread(StartMainPage);
}
}
/// <summary>
/// Start the MainPage
/// </summary>
protected void StartMainPage()
{
System.Diagnostics.Debug.WriteLine(string.Format("*****StartMainPage - Current Thread is [{0}]", Thread.CurrentThread.ManagedThreadId.ToString()));
MainPage = new MainPage();
//Tried this too:
MainPage.Focus();
MainPage.ForceLayout();
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
****BackgroundWork.cs****
using System;
namespace App2
{
public delegate void SimpleEventHandler(object sender, CustomEventArg args);
/// <summary>
/// Status message used to determine when to load the main page
/// </summary>
public enum BWStatus
{
Begin,
Working,
Completed
}
/// <summary>
/// Event arg used to pass status to the OnBackgroundWorkStatusChange event
/// </summary>
public class CustomEventArg : EventArgs
{
public CustomEventArg(BWStatus status) : base()
{
Status = status;
}
public BWStatus Status
{
get; set;
}
}
/// <summary>
/// Abstract class used to act as a base class to demonstrate my setup
/// </summary>
public abstract class BackgroundWork
{
public event SimpleEventHandler OnBackgroundWorkStatusChange;
public BackgroundWork()
{
OnBackgroundWorkStatusChange += BackgroundWork_OnBackgroundWorkStatusChange;
}
protected virtual void FireOnBackgroundWorkStatusChange(object sender, CustomEventArg args)
{
OnBackgroundWorkStatusChange(sender, args);
}
public virtual void InitializeBackgroundWork()
{
System.Diagnostics.Debug.WriteLine("********: BaseClass: Initialize Background Work");
FireOnBackgroundWorkStatusChange(this, new CustomEventArg(BWStatus.Begin));
ContinueBackgroundWork();
FireOnBackgroundWorkStatusChange(this, new CustomEventArg(BWStatus.Completed));
}
protected virtual void ContinueBackgroundWork()
{
System.Diagnostics.Debug.WriteLine("********: BaseClass: Continue Background Work");
FireOnBackgroundWorkStatusChange(this, new CustomEventArg(BWStatus.Working));
}
private void BackgroundWork_OnBackgroundWorkStatusChange(object sender, CustomEventArg args)
{
}
}
/// <summary>
/// Class used to do background work
/// </summary>
public class BackgroundWorkSubclass : BackgroundWork
{
public BackgroundWorkSubclass() : base()
{
}
public override void InitializeBackgroundWork()
{
base.InitializeBackgroundWork();
System.Diagnostics.Debug.WriteLine("********: SubClass: Initialize Background Work");
//Do some more initializing
}
protected override void ContinueBackgroundWork()
{
base.ContinueBackgroundWork();
System.Diagnostics.Debug.WriteLine("********: SubClass: Continue Background Work");
//Continue necessary work
}
}
}
****MainPage.xaml****
<?xml version="1.0" encoding="utf-8" ?>
<StackLayout>
<!-- Place new controls here -->
<Label
HorizontalOptions="Center"
Text="Welcome to Xamarin.Forms! WOOT!!!"
VerticalOptions="CenterAndExpand" />
</StackLayout>
****MainPage.xaml.cs****
using Xamarin.Forms;
namespace App2
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
//System.Diagnostics.Debug.WriteLine("********: MainPage Starting");
}
}
}
How to detect fake location in Xamarin Forms
Hi Team,
I am developing one xamarin form app in which i am taking current lat long of user (GPS) using xamarin essentials. Here i want to stop user sending fake location using MOCK setting or Any Fake GPS APP.
Android:- To achieve this , i have created dependency service but always getting mock location as false using IsFromMockProvider.
I have tested it by Switch ON the Mock location APP named "FAKE GPS". My app still capturing fake location when user use it otherwise it gets real location.
Below is the code i have written
BELOW IS SHARED .NET CODE
1. Interface added
using System;
namespace SmartAttendance.Interfaces
{
public interface IMockLocation
{
Boolean IsMockLocation(Xamarin.Essentials.Location location);
}
}
//Calling Part
if(Device.RuntimePlatform == Device.Android)
{
mock = DependencyService.Get<IMockLocation>().IsMockLocation(position); //Here always getting mock as false even tried fake gps app //
}
BELOW IN ANDRIOD MAIN ACTIVITY
[assembly: Xamarin.Forms.Dependency(typeof(SmartAttendance.Droid.Mock))]
namespace SmartAttendance.Droid
{
public class Mock : IMockLocation
{
public Boolean IsMockLocation(Xamarin.Essentials.Location location) //Copying ESSENTIAL VARIABLE TO ANDRIOD LOCATION VARIABLE
{
Boolean isMock = false;
Context context = Android.App.Application.Context;
Location alocation = new Location("");
alocation.Latitude = location.Latitude;
alocation.Longitude =location.Longitude;
alocation.Accuracy = (float)location.Accuracy;
alocation.Altitude = (float) location.Altitude;
alocation.Speed = (float) location.Speed;
alocation.Time = location.Timestamp.Ticks;
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBeanMr2)
isMock = alocation.IsFromMockProvider; //using marshmallow so this part is executing
else
isMock = Settings.Secure.GetString( context.ContentResolver, Settings.Secure.AllowMockLocation).Equals("0"); //this is below jellybean
return isMock;
}
}
}
FOR IOS : NOT tried any thing yet. As i know its not much easy to set mock location in IOS as compare to ANDRIOD. But If any body can provide any thing it will be higly appreciable
So, Overall tried lot of things but couldn't succeed. Please help what wrong i am doing to stop sending Fake location.
Xamarin Forms ADMob (Firebase.ADS) Not Show
Hello, I have a problem.
I am using the Firebase.ADS plugin to add ads to my application however I am getting this error message and the advertisement is not displayed!
I'm in a .netstandard2.0 project
12-29 22:05:30.118 I/Ads (24010): Ad failed to load : 3
I need Help Please!
Why is a cached ImageSource preventing a page using the ImageSource from being freed?
As I use certain images repeatedly (e.g. for checkboxes, expanders etc), I added some caching a while back. Caching instances of Image caused a problem as there would be multiple references to the same Image object, but caching ImageSource seemed to be ok (although I haven’t measured yet whether there is any benefit, and I will replace it with the FFImageLoading package soon anyway).
However, I have noticed a memory leak, where pages making use of a cached ImageSource do not get freed up. I may need coffee, but I’m not spotting why this is the case. I would like to understand this before replacing the code with FFImageLoading.
I have a class MyAppToggleImageButton that has a constructor that is passed two ImageSource values. Those ImageSource values are obtained from a cache and used in a page as follows (shortened to show the relevant bits):
public class ExperimentationPageView : MyAppContentPageView
{
private MyAppToggleImageButton _btnCheck;
public ExperimentationPageView()
{
_btnCheck = new MyAppToggleImageButton(
MyAppImageCache.TheInstance.UncheckedCheckboxMediumButtonImageSource,
MyAppImageCache.TheInstance.CheckedCheckboxMediumButtonImageSource,
initiallyChecked)
{
};
// other stuff here
}
}
The MyAppToggleImageButton class looks like this (shortened to show the relevant bits):
public class MyAppToggleImageButton : MyAppTemplatedContentView // based on the XLabs templated content view
{
private Image _toggledImage;
private Image _untoggledImage;
// other stuff here
public MyAppToggleImageButton(
ImageSource untoggledImageSource,
ImageSource toggledImageSource,
bool initiallyToggled)
: base()
{
if (Instance == null)
{
Instance = new DataTemplate(
() =>
{
int imageWidth = _inDepthDebugging ? 22 : 44;
_toggledImage = new Image
{
Aspect = Aspect.AspectFit,
Source = toggledImageSource, // leaks resources
InputTransparent = true,
WidthRequest = imageWidth
};
_untoggledImage = new Image
{
Aspect = Aspect.AspectFit,
Source = untoggledImageSource, // leaks resources
InputTransparent = true,
WidthRequest = imageWidth
};
Binding untoggledBinding = new Binding
{
Source = this,
Path = nameof(MyAppToggleImageButton.IsToggled),
Mode = BindingMode.OneWay,
Converter = MyAppBooleanToDoubleTrueToZeroFalseToOneConverter.Instance
};
_untoggledImage.SetBinding(
Image.OpacityProperty, untoggledBinding); // TODO - change this back
Binding toggledBinding = new Binding
{
Source = this,
Path = nameof(MyAppToggleImageButton.IsToggled),
Mode = BindingMode.OneWay,
Converter = MyAppBooleanToDoubleTrueToOneFalseToZeroConverter.Instance
};
_toggledImage.SetBinding(
Image.OpacityProperty, toggledBinding);
_grid = new Grid
{
BackgroundColor = this.BackgroundColor, // TODO - add binding for this
ClassId = "KCI_Grid",
ColumnDefinitions = new ColumnDefinitionCollection(),
ColumnSpacing = 0,
HeightRequest = 44,
HorizontalOptions = LayoutOptions.Start,
IsClippedToBounds = true,
IsVisible = true,
MinimumHeightRequest =
ViewsUsingXamarinForms.MyAppViewRelatedConstants.MinimumHeightOfTappableObject,
MinimumWidthRequest =
ViewsUsingXamarinForms.MyAppViewRelatedConstants.MinimumWidthOfTappableObject,
Opacity = 1.0,
Padding = 0,
RowDefinitions = new RowDefinitionCollection(),
RowSpacing = 0,
VerticalOptions = LayoutOptions.Center,
WidthRequest = 44,
};
_grid.ColumnDefinitions.Add(new ColumnDefinition {Width = imageWidth});
_grid.RowDefinitions.Add(new RowDefinition {Height = imageWidth});
_grid.Children.Add(_toggledImage, 0, 1, 0, 1);
_grid.Children.Add(_untoggledImage, 0, 1, 0, 1);
this.HorizontalOptions = LayoutOptions.StartAndExpand;
this.VerticalOptions = LayoutOptions.FillAndExpand;
this.Padding = 0;
return _grid;
});
}
base.ContentTemplate = Instance;
} // constructor
}
When the page is popped from the navigation stack, the ExperimentationPageView object is not freed up.
The page is only freed if I do:
_toggledImage.Source = null;
_untoggledImage.Source = null;
or, if I simply pass in new ImageSource values rather than cached ImageSource values, the page is freed ok.
So, the question is, why do the pages not get garbage collected if I am using cached ImageSource values, and if I don’t explicitly set the ImageSource properties back to null? Ok, the ImageSource values would have a usage count that won’t go down to zero, but why would that stop the page being freed?
Hoping this is not a question that a mug of coffee would solve… :-)
HotReload LiveReload LiveXaml [Mac] [Windows] [nuget package] [opensource]
Hi all
I want to introduce a nuget package which allows reloading XAML views from Visual Studio on your running app.
This package works for Mac too!
How to I change the selected text color of Hamburger item
i want to change the text color of selected item in MAster detail page???
I can not execute the sample of Hello, Android: Quickstart or Multiscreen
I have downloaded but Hello Android: Quickstart and Multiscreen. When I attempt to execute phoneword.sin I get message ONE OR MORE PROJECTS IN THESOLUTION WERE NOT LOADED CORRECTED. I get the same message from but the Quickstart and the Multiscreen Deep Dive. What must I do to get around this problem?
How to change the top color of IOS app(Color at the phone battery icon)
One screenshot of my xamarin forms ios app is adding below. I want the change the color on the top part, I mean on the color at the battery icon. Currently, it is white, I need it as yellow.
For getting the top padding I added the following code on my XAML:
<StackLayout>
<StackLayout.Padding>
<OnPlatform x:TypeArguments="Thickness"
Android="0, -10, 0, 0"
WinPhone="0, -10, 0, 0"
iOS="0, 15, 0, 0"/>
</StackLayout.Padding>
</StackLayout>
If I remove above code, my app icons and battery icon in the phone get overlap. So How can I change the white color on top?
Open Source or recommended UI Kit / components?
Hi Everyone,
Just wondering if you have an recommendations on any open source or paid for UI Kits and components?
These are the ones that I am currently aware of:
- GrialKit (best looking I think)
- OpenUIKit (but has been pulled from GitHub?)
- Crosslight
- SyncFusion (most functionality?)
- Tekerik
- GrapeCity
- Microcharts
Kind Regards
Carl
How to Use brezier curve in xamarin forms.
i Want to clip the path...like this
how to do it
How to open default contacts app in xamrin forms?
How to open default contacts app in xamrin forms?
How to design a radial progress bar in xammarin forms
Hi Community...
I need to design a radial progress bar with increase and decrease options
How to achieve below like
Please share sample code
Thank you
WebView/HybridWebView Context Menu
Is there any way to show the context menu? especially ios.
do you have an idea or sample? can you please share?
Thanks
How to create a Rich Text box with or without web view in xamarin forms?
I want create a Rich Text box with or without web view in xamarin forms. I tried many examples but none of that worked for me. The examples are
https://github.com/XAM-Consulting/TEditor
The problem with this example was it is too slow for me and it was not editing my text at all. And it was getting crashed numerous times. So I tried to follow this example
https://forums.xamarin.com/discussion/95318/rich-text-box-in-xamarin-forms
but the code by Adam.Else gave me lots of bugs and it was not working. I have reported the bug in stackoverflow. As you can see this link below-
I don't have any clue how to fix this. Any suggestions?
Imran_Idrees
How to use google android and IOS places API in xamarin forms to search places and set pins. Please tell me I want to search places and get latitude and longitude to create polygons. Is this possible?
How to build those contorls? (3 type of controls)
Hi guys. Im pretty new in Xamarin.
So i need to build a few pages, and i have a problem with understanding - how to build some controls.
1) Elements for list view. This is how i need to show result of search, or items (like store items)
If I need to use grid? Or cells? - I just dont know(((
(Or maybe Frame - because here I need rounded corners???)
2) Second is Button
Here is Image on left side and text -- this feature supported in standart button. But i need arrow on the right side
- I need rounder corners.
- (Its can be top corners, or bottom corners, or both of them)
And this is simple form for user.
Laso Rounded corners on top and bot elements.
Guys please help me.
Thank you.
How to add a TapGestureRecognizer in code behind for an Image control
Hi,
I have designed a stacklayout with images as per the code below
var mainLayout = new StackLayout { Spacing = 15, Children = { new Image { Source = "Image1.png", WidthRequest = 25, HeightRequest = 25, }, new Image { Source = "Image2.png", WidthRequest = 25, HeightRequest = 25, }, new Image { Source = "Image3.png", WidthRequest = 25, HeightRequest = 25, }, new Image { Source = "Image4.png", WidthRequest = 25, HeightRequest = 25, }, } };
I want to add a tap gesture recognizer for each image. How can it be done, and also how to identify which image was tapped.
Any suggestions would be grateful.
Is there any way to give an id for each image similar to x:Name="image1" in XAML.
Thanks,
Rajesh.
In .Net Standard 2.0 how I call specific fuctions like camera or open a file?
I would like to watch a video or anything that shows step-by-step how I can implement specific functions for each platform (iOS / Android). I find only snippets of code, but never a complete example application with explanation. Using .Net Standard as a project.
For example. Why do I need to save a pdf in the directory to open it? Why can not I open directly from the byte array coming from my WebAPI?
I've seen several posts and everyone needs to save it.
tks.
Firebase Performance Monitoring SDK for Xamarin Forms
Hello,
I am looking for Firebase Performance Monitoring SDK for my Xamarin Forms app.
but i am not getting any where. now i have doubt, SDK is available for xamarin forms app or not.
Not able to find this sdk for Xamarin.Android nor Xamarin.iOS.
If any one know about this please help me to achieved this.
Thank you.