How to display months and days in Vietnamese in DatePickerDialog? - xamarin

How to display months and days in Vietnamese in DatePickerDialog for Android and DatePicker in IOS when the app language to Vietnamese in Xamarin forms
Android:
protected override DatePickerDialog CreateDatePickerDialog(int year, int month, int day)
{
pickerDialog = new DatePickerDialog(Context, (o, e) =>
{
datePicker.Date = e.Date;
((IElementController)datePicker).SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
}, year, month, day);
//ok
pickerDialog.SetButton((int)DialogButtonType.Positive, AppResources.AlertDismiss, OnDone);
//cancel
pickerDialog.SetButton((int)DialogButtonType.Negative, AppResources.PickerCancelText, OnCancel);
return pickerDialog;
}
IOS: suggest me how to do in IOS?

If I understand correctly , do you want to show English formatting for the DatePicker?
If so you can modify the Locale for the datepicker in custom renderer .
iOS Solution
[assembly: ExportRenderer(typeof(DatePicker), typeof(MyRenderer))]
namespace FormsApp.iOS
{
class MyRenderer : DatePickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
{
base.OnElementChanged(e);
if(Control != null)
{
UIDatePicker picker = Control.InputView as UIDatePicker;
picker.Locale = new NSLocale("us");
}
}
}
}
Before
After
If you want the Datepicker only display month and day for selecting item , it could be a little complex , because iOS does not provide the option/mode to achieve that , you need to create a view and controller that implement the UIPickerViewDelegate and create your own .
Refer to
https://stackoverflow.com/a/412754/8187800.
https://stackoverflow.com/a/24971192/8187800.
Android Solution
Add the following code into OnCreate in MainActivity class .
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
//this code
Locale locale = Locale.Us;
Locale.SetDefault(Locale.Category.Format, locale);
Configuration config = this.Resources.Configuration;
config.SetLocale(locale);
CreateConfigurationContext(config);
LoadApplication(new App());
}
Before
###After
Refer to
DatePickerDialog in arabic language
Set Android DatePicker title language

Related

Is there any way in Xamarin Forms to change the background color of a dialog box?

Here's what my dialog box looks like with a dark theme.
Does anyone know of a way that the colors could be changed in a Xamarin Forms app so that the dialog displays with white text on a dark background?
Does anyone have an idea what the problem might be?
Option 1
You could change it in specific platforms by using DependencyService
in forms
create the interface
using Xamarin.Forms;
namespace xxx
{
public interface IPopUp
{
void Popup(string title, string message,Color titleColor,Color messageColor, EventHandler handler);
}
}
in iOS
using System;
using System.Text;
using xxx.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using xxx;
[assembly: Dependency(typeof(PopupImplemention))]
namespace xxx.iOS
{
public class PopupImplemention : IPopUp
{
public void Popup(string title, string message, Color titleColor, Color messageColor, EventHandler handler)
{
UIAlertController alertController = UIAlertController.Create(title,message,UIAlertControllerStyle.Alert);
var firstAttributes = new UIStringAttributes
{
ForegroundColor =titleColor.ToUIColor(),
};
var secondAttributes = new UIStringAttributes
{
ForegroundColor =messageColor.ToUIColor(),
};
alertController.SetValueForKey(new NSAttributedString(title, firstAttributes), new NSString("attributedTitle"));
alertController.SetValueForKey(new NSAttributedString(message, secondAttributes), new NSString("attributedMessage"));
UIAlertAction cancelAction = UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,null);
UIAlertAction okAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default,(sender)=> { handler?.Invoke(sender, new EventArgs()) ; });
alertController.AddAction(cancelAction);
alertController.AddAction(okAction);
var currentViewController = topViewControllerWithRootViewController(UIApplication.SharedApplication.Delegate.GetWindow().RootViewController);
currentViewController.PresentViewController(alertController,true,null);
}
UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
{
if (rootViewController is UITabBarController)
{
UITabBarController tabBarController = (UITabBarController)rootViewController;
return topViewControllerWithRootViewController(tabBarController.SelectedViewController);
}
else if (rootViewController is UINavigationController)
{
UINavigationController navigationController = (UINavigationController)rootViewController;
return topViewControllerWithRootViewController(navigationController.VisibleViewController);
}
else if (rootViewController.PresentedViewController != null)
{
UIViewController presentedViewController = rootViewController.PresentedViewController;
return topViewControllerWithRootViewController(presentedViewController);
}
else
{
return rootViewController;
}
}
}
}
in Android
in MainActivity
public static MainActivity Intance;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Intance = this;
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
using Xamarin.Forms;
using xxx;
using xxx.Droid;
using Android;
using System;
using Xamarin.Forms.Platform.Android;
using Android.Support.V7.App;
using Android.Text;
[assembly: Dependency(typeof(PopupImplemention))]
namespace xxx.Droid
{
public class PopupImplemention : IPopUp
{
public void Popup(string title, string message, Color titleColor, Color messageColor, EventHandler handler)
{
// because html.string could not support format string , so you need to set the color directly in the string with a static value
Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(MainActivity.Intance);
alert.SetTitle(Html.FromHtml(string.Format("<font color='#ff0000'>{0}</font>" ,title),FromHtmlOptions.ModeLegacy));
alert.SetMessage(Html.FromHtml(string.Format("<font color='#00ff00'>{0}</font>", message), FromHtmlOptions.ModeLegacy));
alert.SetPositiveButton("OK", (senderAlert, args) =>
{
handler?.Invoke(senderAlert, args);
});
alert.SetNegativeButton("Cancel", (senderAlert, args) =>
{
});
Android.Support.V7.App.AlertDialog dialog = alert.Create();
dialog.Show();
}
}
}
And call it in forms
DependencyService.Get<IPopUp>().Popup("Title","xxxxxxxxxxxx",Color.Red,Color.Blue,(sen,args)=> {
// handle the logic when clikc the OK button
});
Option 2
You could use the plugin Rg.Plugins.Popup ,which allows to open Xamarin.Forms pages as a popup that can be shared across iOS, Android and UWP . And you can customize it as you want .

OneSignal Xamarin.Forms HandleNotificationOpened redirect to notification specific page

in my Xamarin.Forms project I use OneSignal for notifications. In iOS Xamarin.Forms.Application.Current.MainPage = new NavigationPage(new NotificationPage()); worked but in Android this not work. I tried to use messaging center to communicate with PCL project. It worked when app is background but not working when app is closed. How can I redirect notification specific page when notification received in Android? Thanks
Note : Code edited and issue solved, I used shared preferences to control if app launched from notification or not. Then I Load xamarin.Forms application.
You can use below method before LoadApplication() method is called.
if (Intent.Extras != null)
{
foreach (var key in Intent.Extras.KeySet())
{
if (key != null)
{
var value = Intent.Extras.GetString(key);
Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
}
}
}
LoadApplication(new App());
You have to set intent.putExtra() method in OnMessageReceivedMethod().
intent.PutExtra("Key", "value");
Then you can use redirection in App.xaml.cs file based on this key value. Because in android when notification is open while app is reinitialized.
I think you don't need to put below condition.
if (extrasList[0] == "true")
{
LoadApplication(new App(true));
}
else
{
LoadApplication(new App(false));
}
First Store your value global level so you can use it in App.cs file. Just use below code to handle page navigation in App() class like.
if (Device.RuntimePlatform == Device.Android)
{
if (YourKey == "true")
{
//handle that page navigation
}
else
{
//Default Page of App
}
}
Note : Code edited and issue solved, I used shared preferences to control if app launched from notification or not. Then I Load xamarin.Forms application
public class MainActivity :
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
InitializeUI();
global::Xamarin.Forms.Forms.Init(this, bundle);
global::Xamarin.FormsMaps.Init(this, bundle);
ImageCircleRenderer.Init();
tV = new TextView(this);
resources = this.Resources;
OneSignal.Current.StartInit("***APP ID***")
.InFocusDisplaying(OSInFocusDisplayOption.Notification)
.HandleNotificationReceived(HandleNotificationReceived)
.HandleNotificationOpened(HandleNotificationOpened)
.EndInit();
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
var LaunchFromNotification = prefs.GetString("is_notification_received", "false");
if (LaunchFromNotification == "true")
{
LoadApplication(new App(true));
}
else
{
LoadApplication(new App(false));
}
OneSignal.Current.IdsAvailable(IdsAvailable); //Lets you retrieve the OneSignal player id and push token.
}
}
private static void HandleNotificationOpened(OSNotificationOpenedResult result)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Android.App.Application.Context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("is_notification_received", "true");
editor.Apply();
}
protected override void OnResume()
{
base.OnResume();
ISharedPreferences prefs =
PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor editor = prefs.Edit();
editor.Remove("is_notification_received");
editor.PutString("is_notification_received", "false");
editor.Apply();
}

Button Clicked in Xamarin Android to call Xamarin.Forms.Page?

I need to call a Xamarin.Forms Page through an Activity in Xamarin.Android.
I had used [Java.Interop.Export("btnOne1Click")] to call the Xamarin.Forms Page.
The code runs without errors if I use App.Current.MainPage = new RootPage(); But it does not navigate to that Page.
I don't want to call the [Java.Interop.Export("btnOne1Click")] on MainActivity.
[Activity(Label = "FailureActivity")]
public class FailureActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
RequestWindowFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Failure);
Button button = FindViewById<Button>(Resource.Id.txt_go_onjobs);
}
[Java.Interop.Export("btnOne1Click")]
public void btnOne1Click(Android.Views.View v)
{
try
{
Xamarin.Forms.Forms.Context.StartActivity(typeof(RootPage));
}
catch(Exception ex)
{ }
}
}
Xamarin forms runs on one activity, which is most like your main activity.
There are two sample projects that show you how to communicate between native and form parts of the code, which can be found here:
https://github.com/xamarin/xamarin-forms-samples/tree/master/Forms2Native
https://github.com/xamarin/xamarin-forms-samples/tree/master/Native2Forms
However, to answer your question, you would do something like the following:
button = FindViewById<Button> (Resource.Id.txt_go_onjobs);
button.Click += (sender, e) => {
// this is your Xamarin.Forms screen
StartActivity(typeof(FormsActivity));
};
Now, in your FormsActivity call this:
[Activity (Label = "FormsActivity")]
public class FormsActivity : Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new App ());
}
}

Xamarin.Forms custom Android NavigationPageRenderer title and subtitle

Currently working on a project where I want to use AppCompat and have a requirement setting title and subtitle on most of the pages.
It doesn't work using AppCompat at all - neither setting the properties nor using a custom view.
When not using AppCompat both works as expected. The full source code is available here so just run the app if you're curious :)
using System.ComponentModel;
using Android.App;
using Android.Widget;
using App1.Droid.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
#if __APPCOMPAT__
using NavigationRenderer = Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer;
#else
using NavigationRenderer = Xamarin.Forms.Platform.Android.NavigationRenderer;
#endif
[assembly: ExportRenderer(typeof(NavigationPage), typeof(NavigationPageRenderer))]
namespace App1.Droid.Renderers
{
public class NavigationPageRenderer : NavigationRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
{
base.OnElementChanged(e);
SetCustomView(e.NewElement.CurrentPage.GetType().Name);
}
private void SetCustomView(string view)
{
var activity = (Activity)Context;
#if __APPCOMPAT__
var actionBar = ((FormsAppCompatActivity)Context).SupportActionBar;
#else
var actionBar = activity.ActionBar;
#endif
actionBar.Title = view;
actionBar.Subtitle = " -> " + view;
var abv = new LinearLayout(activity)
{
Orientation = Orientation.Vertical
};
var main = new TextView(activity)
{
Text = view,
};
main.SetTextColor(Color.Aqua.ToAndroid());
main.SetPadding(4, 4, 2, 6);
abv.AddView(main);
abv.AddView(new TextView(activity)
{
Text = " -> " + view
});
actionBar.SetDisplayShowCustomEnabled(true);
actionBar.CustomView = abv;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals("CurrentPage"))
{
SetCustomView(((NavigationPage)sender).CurrentPage.GetType().Name);
}
}
}
}
Edit: Thanks #jimmgarr. Altered the code slightly to keep alternating between AppCompbat and "normal mode". The code is available here
So it looks like the NavigationPage uses its own Toolbar instance. That's why setting the properties on SupportActionBar isn't doing anything.
I was able to get it working by overriding OnViewAdded() to get a reference to the new Toolbar when it's added:
public override void OnViewAdded(Android.Views.View child)
{
base.OnViewAdded(child);
if (child.GetType() == typeof(Support.Toolbar))
toolbar = (Support.Toolbar)child;
}
Then using the reference inside SetCustomView() to set only the Subtitle since the Title is already set automatically.
Here's the complete renderer class :)

I want to add my own image to switch Control in ios using Xamarin forms

I tried to add my own image to switch Control in xamarin forms using rendering concept but i am unable to override the existing image.Below is my code.
In shared project i added code like this
Switch switcher = new ExtendedSwitchnew();
and in ios
[assembly: ExportRenderer(typeof(ExtendedSwitchnew),typeof(SwitchRenderernew))]
namespace test.iOS
{
public class SwitchRenderernew :SwitchRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
{
base.OnElementChanged(e);
if (Control != null)
{
UIImage imgon = UIImage.FromFile("Images/switchon.png");
UIImage imgoff = UIImage.FromFile("Images/switchoff.png");
Control.OnImage = imgon;
Control.OffImage = imgoff;
}
}
}
}
Help me.Thanks in advace.

Resources