For the first time I'm restricting the onAppearing() methods in all child pages of tabbed page. I need to call the onAppearing() when I change the tab. For that, I'm using OnCurrentPageChanged() to call the onAppearing() method.
When I change the tab, I'm calling the OnCurrentPageChanged() and giving them access to run the onAppearing() functionality. onAppearing() is calling before calling the OnCurrentPageChanged().
TabbedPage code:
public partial class VendorScheduleTabbedPage : Xamarin.Forms.TabbedPage
{
public int isCount;
public VendorScheduleTabbedPage ()
{
InitializeComponent ();
Xamarin.Forms.Application.Current.Properties["dayOnAppear"] = false;
Xamarin.Forms.Application.Current.Properties["weekOnAppear"] = false;
Xamarin.Forms.Application.Current.Properties["monthOnAppear"] = false;
On<Android>().SetBarItemColor(value: Color.FromHex("#6699FF"));
On<Android>().SetBarSelectedItemColor(value: Color.Orange);
}
override protected void OnCurrentPageChanged()
{
isCount = 1;
if (this.CurrentPage.Title == "Week")
{
Xamarin.Forms.Application.Current.Properties["weekOnAppear"] = true;
}
if (this.CurrentPage.Title == "Month")
{
Xamarin.Forms.Application.Current.Properties["monthOnAppear"] = true;
}
else
{
Xamarin.Forms.Application.Current.Properties["dayOnAppear"] = true;
}
base.OnCurrentPageChanged();
}
}
}
Week Page code(child page):
public WeekSchedulePage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
timeSlot = new List<VendorScheduleTimeSlot>();
scheduleSlots = new List<VendorScheduleTimeSlot>();
lstVendorsData = new List<ScheduledCustomersVM>();
SortedList = new List<ScheduledCustomersVM>();
scheduledCustomersList = new List<ScheduledCustomersVM>();
rescheduledCustomersList = new List<RescheduledCustomersVM>();
ConfirmBtn.IsVisible = true;
ConfirmBtn.IsEnabled = false;
vendorDayAndHoursDataVM = new VendorDayAndHoursDataVM();
lstDaysAndHours = new List<VendorDayAndHoursDataVM>();
lstQuestionsData = new List<VendorQuestionsDataVM>();
overlay.IsVisible = false;
Alert.IsVisible = false;
presentWeekDay.Text = DateTime.Now.ToString("dddd, dd MMMM yyyy");
currentDayName = DateTime.Now.DayOfWeek.ToString();
currentDate = DateTime.Parse(presentWeekDay.Text);
}
protected override void OnAppearing()
{
var isAppear = Convert.ToBoolean(Application.Current.Properties["weekOnAppear"].ToString());
if (isAppear == true)
{
ConfirmBtn.IsVisible = true;
ConfirmBtn.IsEnabled = false;
overlay.IsVisible = false;
Alert.IsVisible = false;
Application.Current.Properties["dayOnAppear"] = true;
Application.Current.Properties["monthOnAppear"] = true;
ConfirmBtn.IsEnabled = false;
scheduledCustomersList.Clear();
rescheduledCustomersList.Clear();
presentWeekDay.Text = DateTime.Now.ToString("dddd, dd MMMM yyyy");
currentDayName = DateTime.Now.DayOfWeek.ToString();
weekwiseTimeslotClick();
base.OnAppearing();
}
}
Here I need to call OnCurrentPageChanged() method first instead of the OnApearing() method. And OnCurrentPageChanged() will give the bool value to perform the code which is in OnApearing() method.
In Android, onAppearing is called before OnCurrentPageChanged while in iOS OnCurrentPageChanged is called before onAppearing.
1.As jgoldberger suggested, you can call method in each Page after CurrentPageChanged:
override protected void OnCurrentPageChanged()
{
if (this.CurrentPage.Title == "Week")
{
Xamarin.Forms.Application.Current.Properties["weekOnAppear"] = true;
NavigationPage naviPage = this.Children[0] as NavigationPage;
WeekPage page = naviPage.RootPage as WeekPage;
page.test();
}else if (this.CurrentPage.Title == "Month")
{
Xamarin.Forms.Application.Current.Properties["monthOnAppear"] = true;
NavigationPage naviPage = this.Children[1] as NavigationPage;
MonthPage page = naviPage.RootPage as MonthPage;
page.test();
}
else
{
Xamarin.Forms.Application.Current.Properties["dayOnAppear"] = true;
NavigationPage naviPage = this.Children[2] as NavigationPage;
DayPage page = naviPage.RootPage as DayPage;
page.test();
}
base.OnCurrentPageChanged();
}
}
2.You can use messaging-center to notify specific page to perform some actions after CurrentPageChanged:
override protected void OnCurrentPageChanged()
{
string testStr;
if (this.CurrentPage.Title == "Week")
{
testStr = "Week";
}else if (this.CurrentPage.Title == "Month")
{
testStr = "Month";
}
else
{
testStr = "Day";
}
MessagingCenter.Send<object, string>(new object(), "CurrentPageChanged", testStr);
base.OnCurrentPageChanged();
}
And in each page:
public partial class MonthPage : ContentPage
{
public MonthPage()
{
InitializeComponent();
MessagingCenter.Subscribe<object, string>(new object(), "CurrentPageChanged", async (sender, arg) =>
{
if (arg == "Month")
{
Console.WriteLine(arg);
//do something
}
});
}
public void test() {
Console.WriteLine("test");
//do something
}
}
BTW, you should use if...else if...else instead of if...if...else in your control statement.
Related
I'm having a Xamarin Forms application where I could successfully add banner ads and native ads for the android with custom renderers using Google AdMob NuGet. What I'm trying to achieve here is to make them work on IOS, I managed to do that (I suppose as I'm receiving test ads) with banner but when it comes to native, I get unified native ad and it never renders...
I'm using it inside of a custom listview data template which I thought it might cause an issue, so I tried using it in the page itself but no luck, same issue.
Here is my IOS renderer so far:
[assembly: ExportRenderer(typeof(NativeAdMobUnit), typeof(NativeAdMobUnitRenderer))]
namespace Example.iOS.Components
{
public class NativeAdMobUnitRenderer : ViewRenderer<NativeAdMobUnit, NativeExpressAdView>
{
protected override void OnElementChanged(ElementChangedEventArgs<NativeAdMobUnit> e)
{
base.OnElementChanged(e);
if (e.NewElement == null)
return;
if (e.OldElement == null)
{
CreateAdView(this, e.NewElement.AdUnitId);
}
}
private void CreateAdView(NativeAdMobUnitRenderer renderer,String AdUnitId)
{
if (Element == null) return;
var loader = new AdLoader(
AdUnitId,
GetVisibleViewController(),
new AdLoaderAdType[] { AdLoaderAdType.UnifiedNative },
new AdLoaderOptions[] {
new NativeAdViewAdOptions {PreferredAdChoicesPosition = AdChoicesPosition.TopRightCorner}
});
var request = Request.GetDefaultRequest();
request.TestDevices = new string[] { Request.SimulatorId };
try
{
loader.Delegate = new MyAdLoaderDelegate(renderer);
Device.BeginInvokeOnMainThread(() => {
loader.LoadRequest(Request.GetDefaultRequest());
});
}
catch(Exception ex)
{
}
}
private UIViewController GetVisibleViewController()
{
var windows = UIApplication.SharedApplication.Windows;
foreach (var window in windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
private class MyAdLoaderDelegate : NSObject, IUnifiedNativeAdLoaderDelegate
{
private readonly NativeAdMobUnitRenderer _renderer;
public MyAdLoaderDelegate(NativeAdMobUnitRenderer renderer)
{
_renderer = renderer;
}
public void DidReceiveUnifiedNativeAd(AdLoader adLoader, UnifiedNativeAd nativeAd)
{
Debug.WriteLine("DidReceiveUnifiedNativeAd");
}
public void DidFailToReceiveAd(AdLoader adLoader, RequestError error)
{
Debug.WriteLine("DidFailToReceiveAd");
}
public void DidFinishLoading(AdLoader adLoader)
{
Debug.WriteLine("DidFinishLoading");
}
}
}
}
And that's the same but for Android which is working as expected:
[assembly: ExportRenderer(typeof(NativeAdMobUnit), typeof(NativeAdMobUnitRenderer))]
namespace Example.Droid.Renderers
{
public class NativeAdMobUnitRenderer : ViewRenderer
{
public NativeAdMobUnitRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
{
base.OnElementChanged(e);
if (Control == null)
{
NativeAdMobUnit NativeAdUnit = (NativeAdMobUnit)Element;
var adLoader = new AdLoader.Builder(Context, NativeAdUnit.AdUnitId);
var listener = new UnifiedNativeAdLoadedListener();
listener.OnNativeAdLoaded += (s, ad) =>
{
try
{
var root = new UnifiedNativeAdView(Context);
var inflater = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService);
var adView = (UnifiedNativeAdView)inflater.Inflate(Resource.Layout.ad_unified, root);
populateUnifiedNativeAdView(ad, adView);
SetNativeControl(adView);
}
catch
{
}
};
adLoader.ForUnifiedNativeAd(listener);
var requestBuilder = new AdRequest.Builder();
adLoader.Build().LoadAd(requestBuilder.Build());
}
}
private void populateUnifiedNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdView adView)
{
adView.MediaView = adView.FindViewById<MediaView>(Resource.Id.ad_media);
// Set other ad assets.
adView.HeadlineView = adView.FindViewById<TextView>(Resource.Id.ad_headline);
adView.BodyView = adView.FindViewById<TextView>(Resource.Id.ad_body);
adView.CallToActionView = adView.FindViewById<TextView>(Resource.Id.ad_call_to_action);
adView.IconView = adView.FindViewById<ImageView>(Resource.Id.ad_app_icon);
adView.PriceView = adView.FindViewById<TextView>(Resource.Id.ad_price);
adView.StarRatingView = adView.FindViewById<RatingBar>(Resource.Id.ad_stars);
adView.StoreView = adView.FindViewById<TextView>(Resource.Id.ad_store);
adView.AdvertiserView = adView.FindViewById<TextView>(Resource.Id.ad_advertiser);
// The headline and mediaContent are guaranteed to be in every UnifiedNativeAd.
((TextView)adView.HeadlineView).Text = nativeAd.Headline;
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
if (nativeAd.Body == null)
{
adView.BodyView.Visibility = ViewStates.Invisible;
}
else
{
adView.BodyView.Visibility = ViewStates.Visible;
((TextView)adView.BodyView).Text = nativeAd.Body;
}
if (nativeAd.CallToAction == null)
{
adView.CallToActionView.Visibility = ViewStates.Invisible;
}
else
{
adView.CallToActionView.Visibility = ViewStates.Visible;
((Android.Widget.Button)adView.CallToActionView).Text = nativeAd.CallToAction;
}
if (nativeAd.Icon == null)
{
adView.IconView.Visibility = ViewStates.Gone;
}
else
{
((ImageView)adView.IconView).SetImageDrawable(nativeAd.Icon.Drawable);
adView.IconView.Visibility = ViewStates.Visible;
}
if (string.IsNullOrEmpty(nativeAd.Price))
{
adView.PriceView.Visibility = ViewStates.Gone;
}
else
{
adView.PriceView.Visibility = ViewStates.Visible;
((TextView)adView.PriceView).Text = nativeAd.Price;
}
if (nativeAd.Store == null)
{
adView.StoreView.Visibility = ViewStates.Invisible;
}
else
{
adView.StoreView.Visibility = ViewStates.Visible;
((TextView)adView.StoreView).Text = nativeAd.Store;
}
if (nativeAd.StarRating == null)
{
adView.StarRatingView.Visibility = ViewStates.Invisible;
}
else
{
((RatingBar)adView.StarRatingView).Rating = nativeAd.StarRating.FloatValue();
adView.StarRatingView.Visibility = ViewStates.Visible;
}
if (nativeAd.Advertiser == null)
{
adView.AdvertiserView.Visibility = ViewStates.Invisible;
}
else
{
((TextView)adView.AdvertiserView).Text = nativeAd.Advertiser;
adView.AdvertiserView.Visibility = ViewStates.Visible;
}
adView.SetNativeAd(nativeAd);
}
}
public class UnifiedNativeAdLoadedListener : AdListener, UnifiedNativeAd.IOnUnifiedNativeAdLoadedListener
{
public void OnUnifiedNativeAdLoaded(UnifiedNativeAd ad)
{
OnNativeAdLoaded?.Invoke(this, ad);
}
public EventHandler<UnifiedNativeAd> OnNativeAdLoaded { get; set; }
}
}
In my xamarin.forms app, I created a custom camera by using Camera view and custom renders. Everything works fine. In android after the photo capture I can check whether the taken photo contains a face or not.It is done by using Camera.IFaceDetectionListener. My question is how can I achieve this in iOS? I know there is vision API. But I don't want the live face tracking. I just simply want to check whether the taken photo contains face. Any help is appreciated.
My iOS CameraPreview
public class UICameraPreview : UIView, IAVCaptureMetadataOutputObjectsDelegate
{
AVCaptureVideoPreviewLayer previewLayer;
public AVCaptureDevice[] videoDevices;
CameraOptions cameraOptions;
public AVCaptureStillImageOutput stillImageOutput;
public AVCaptureDeviceInput captureDeviceInput;
public AVCaptureDevice device;
public event EventHandler<EventArgs> Tapped;
public AVCaptureSession CaptureSession { get; set; }
public bool IsPreviewing { get; set; }
public AVCaptureStillImageOutput CaptureOutput { get; set; }
public UICameraPreview(CameraOptions options)
{
cameraOptions = options;
IsPreviewing = false;
Initialize();
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (previewLayer != null)
previewLayer.Frame = Bounds;
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
OnTapped();
}
protected virtual void OnTapped()
{
var eventHandler = Tapped;
if (eventHandler != null)
{
eventHandler(this, new EventArgs());
}
}
void Initialize()
{
CaptureSession = new AVCaptureSession();
previewLayer = new AVCaptureVideoPreviewLayer(CaptureSession)
{
Frame = Bounds,
VideoGravity = AVLayerVideoGravity.ResizeAspectFill
};
videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition);
if (device == null)
{
return;
}
NSError error;
captureDeviceInput = new AVCaptureDeviceInput(device, out error);
CaptureSession.AddInput(captureDeviceInput);
var dictionary = new NSMutableDictionary();
dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
stillImageOutput = new AVCaptureStillImageOutput()
{
OutputSettings = new NSDictionary()
};
CaptureSession.AddOutput(stillImageOutput);
Layer.AddSublayer(previewLayer);
CaptureSession.StartRunning();
IsPreviewing = true;
}
// Photo Capturing
public async Task CapturePhoto()
{
try
{
var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);
var jpegData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);
var photo = new UIImage(jpegData);
var rotatedPhoto = RotateImage(photo, 180f);
var img = rotatedPhoto;
CALayer layer = new CALayer
{
ContentsScale = 1.0f,
Frame = Bounds,
Contents = rotatedPhoto.CGImage //Contents = photo.CGImage,
};
CaptureSession.StopRunning();
photo.SaveToPhotosAlbum((image, error) =>
{
if (!string.IsNullOrEmpty(error?.LocalizedDescription))
{
Console.Error.WriteLine($"\t\t\tError: {error.LocalizedDescription}");
}
});
}
catch (Exception ex)
{
}
//MainPage.UpdateSource(UIImageFromLayer(layer).AsJPEG().AsStream());
//MainPage.UpdateImage(UIImageFromLayer(layer).AsJPEG().AsStream());
}
}
My CameraPreviewRenderer
public class CameraPreviewRenderer : ViewRenderer<CameraPreview, UICameraPreview>, IAVCaptureMetadataOutputObjectsDelegate
{
UICameraPreview uiCameraPreview;
AVCaptureSession captureSession;
AVCaptureDeviceInput captureDeviceInput;
AVCaptureStillImageOutput stillImageOutput;
protected override void OnElementChanged(ElementChangedEventArgs<CameraPreview> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
uiCameraPreview.Tapped -= OnCameraPreviewTapped;
}
if (e.NewElement != null)
{
if (Control == null)
{
uiCameraPreview = new UICameraPreview(e.NewElement.Camera);
SetNativeControl(uiCameraPreview);
MessagingCenter.Subscribe<Camera_Popup>(this, "CaptureClick", async (sender) =>
{
try
{
// Using messeging center to take photo when clicking button from shared code
var data = new AVCaptureMetadataOutputObjectsDelegate();
await uiCameraPreview.CapturePhoto();
}
catch (Exception ex)
{
return;
}
});
}
MessagingCenter.Subscribe<Camera_Popup>(this, "RetryClick", (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
uiCameraPreview.CaptureSession.StartRunning();
uiCameraPreview.IsPreviewing = true;
});
});
MessagingCenter.Subscribe<Camera_Popup>(this, "FlipClick", (sender) =>
{
try
{
var devicePosition = uiCameraPreview.captureDeviceInput.Device.Position;
if (devicePosition == AVCaptureDevicePosition.Front)
{
devicePosition = AVCaptureDevicePosition.Back;
}
else
{
devicePosition = AVCaptureDevicePosition.Front;
}
uiCameraPreview.device = uiCameraPreview.videoDevices.FirstOrDefault(d => d.Position == devicePosition);
uiCameraPreview.CaptureSession.BeginConfiguration();
uiCameraPreview.CaptureSession.RemoveInput(uiCameraPreview.captureDeviceInput);
uiCameraPreview.captureDeviceInput = AVCaptureDeviceInput.FromDevice(uiCameraPreview.device);
uiCameraPreview.CaptureSession.AddInput(uiCameraPreview.captureDeviceInput);
uiCameraPreview.CaptureSession.CommitConfiguration();
}
catch (Exception ex)
{
var abc = ex.InnerException.Message;
}
});
uiCameraPreview.Tapped += OnCameraPreviewTapped;
}
}
void OnCameraPreviewTapped(object sender, EventArgs e)
{
if (uiCameraPreview.IsPreviewing)
{
uiCameraPreview.CaptureSession.StopRunning();
uiCameraPreview.IsPreviewing = false;
}
else
{
uiCameraPreview.CaptureSession.StartRunning();
uiCameraPreview.IsPreviewing = true;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Control.CaptureSession.Dispose();
Control.Dispose();
}
base.Dispose(disposing);
}
}
The CoreImage framework has CIDetector that provides image detectors for faces, QR codes, text, .... in which you pass in an image and you get a specific "feature set" back.
Example from Xamarin docs:
var imageFile = "photoFace2.jpg";
var image = new UIImage(imageFile);
var context = new CIContext ();
var detector = CIDetector.CreateFaceDetector (context, true);
var ciImage = CIImage.FromCGImage (image.CGImage);
var features = detector.GetFeatures (ciImage);
Console.WriteLine ("Found " + features.Length + " faces");
re: https://learn.microsoft.com/en-us/dotnet/api/CoreImage.CIDetector?view=xamarin-ios-sdk-12
I am facing issue with Tabbed Page in iOS. I have added 5 navigation pages in the tabbed page. After showing and closing modal, I am not able to change tab on tap. If I hold another tab for 3-4 seconds (long press) then that tab is getting selected. Not sure what is the issue. No logs as well.
The same code is working fine on Android. Please let me know if someone has faced a similar issue.
Home Page code
private bool tabsConfigured = false;
public HomeView (HomeViewModel viewModel)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
if (Device.RuntimePlatform == Device.Android)
{
On<Xamarin.Forms.PlatformConfiguration.Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
On<Xamarin.Forms.PlatformConfiguration.Android>().SetBarItemColor(Color.FromHex("#c1c1c1"));
On<Xamarin.Forms.PlatformConfiguration.Android>().SetBarSelectedItemColor(Color.White);
On<Xamarin.Forms.PlatformConfiguration.Android>().SetIsSwipePagingEnabled(false);
On<Xamarin.Forms.PlatformConfiguration.Android>().SetOffscreenPageLimit(5);
}
else if (Device.RuntimePlatform == Device.iOS)
{
this.BarBackgroundColor = Color.FromHex("#0c293d");
//this.BarTextColor = Color.White;
}
this.ViewModel = viewModel;
this.ViewModel.SwitchTabAction = OnSwitchTabFromViewModel;
#if __IOS__
InitTabs();
#endif
}
protected override void OnAppearing()
{
base.OnAppearing();
#if __ANDROID__
InitTabs();
#endif
}
protected override void OnDisappearing()
{
base.OnDisappearing();
this.ViewModel.SwitchTabAction = null;
}
private void InitTabs()
{
var logService = AutofacUtil.Instance.Resolve<ILogService>();
try
{
if (tabsConfigured) return;
this.Children.Add(this.GetInitialTabPage<DestinationsViewModel>("tab_guide", "Guide"));
this.Children.Add(this.GetInitialTabPage<GroupsViewModel>("tab_chats", "Groups"));
this.Children.Add(this.GetInitialTabPage<ItineraryViewModel>("tab_itineraries", "Itineraries"));
this.Children.Add(this.GetInitialTabPage<ExpenseViewModel>("tab_expenses", "Expenses"));
this.Children.Add(this.GetInitialTabPage<MoreViewModel>("tab_mores", "More"));
#if __ANDROID__
this.BatchCommit();
#endif
tabsConfigured = true; //Important to be here.
//Setting Current Page
if (this.ViewModel.ActiveTab >= 1)
this.CurrentPage = this.Children[this.ViewModel.ActiveTab];
else if (this.ViewModel.ActiveTab == 0) //OnPageChanged doesn't get called for first tab.
{
CurrentPage = this.Children[this.ViewModel.ActiveTab];
OnPageChanged();
}
}
catch (Exception ex)
{
logService.Error(ex);
}
}
public NavigationPage GetInitialTabPage<T>(string icon, string title) where T : BaseCoreViewModel
{
Page page = new TabLoadingPage(typeof(T));
NavigationPage navigationPage = new NavigationPage(page);
navigationPage.Icon = icon;
navigationPage.Title = title;
navigationPage.BarBackgroundColor = Color.FromHex("#0c293d");
navigationPage.BarTextColor = Color.White;
return navigationPage;
}
Code to show Modal. Calling PushModalAsync to show modal.
public class NavigationService : INavigationService
{
private INavigation _mainNavigation = null;
private INavigation _currentTabNavigation = null;
private INavigation _currentModalNavigation = null;
private NavigationPage _currentModalNavPage = null;
public void SetMainXamarinFormsNavigation(INavigation navigation)
{
_mainNavigation = navigation;
}
public void SetTabXamarinFormsNavigation(INavigation navigation)
{
_currentTabNavigation = navigation;
}
public async Task PushAsync<T>(object parameters = null, bool animate = true) where T : BaseCoreViewModel
{
var page = ViewCreator.CreateViewAndViewModelAndCallInit<T>(parameters);
INavigation currentNavigation = null;
if (_currentModalNavigation != null)
currentNavigation = _currentModalNavigation;
else if (_currentTabNavigation != null)
currentNavigation = _currentTabNavigation;
else if (_mainNavigation != null)
currentNavigation = _mainNavigation;
#if __IOS__
var currentPage = currentNavigation.NavigationStack.ElementAt(currentNavigation.NavigationStack.Count - 1);
var oldTitle = currentPage.Title;
currentPage.Title = "Back";
#endif
await currentNavigation.PushAsync(page, animate);
#if __IOS__
currentPage.Title = oldTitle;
#endif
}
public async Task PushModalAsync<T>(object parameters = null, bool animate = true) where T : BaseCoreViewModel
{
if (_mainNavigation == null) return;
#if __ANDROID__
var emptyPage = new FirstEmptyNavPage();
#endif
var startPage = ViewCreator.CreateViewAndViewModelAndCallInit<T>(parameters, true);
#if __ANDROID__
_currentModalNavPage = new NavigationPage(emptyPage);
#else
_currentModalNavPage = new NavigationPage(startPage);
#endif
_currentModalNavPage.Popped += _currentModalNavPage_Popped;
_currentModalNavPage.BarBackgroundColor = Color.FromHex("#0c293d");
_currentModalNavPage.BarTextColor = Color.White;
#if __ANDROID__
await _currentModalNavPage.PushAsync(startPage);
#endif
await _mainNavigation.PushModalAsync(_currentModalNavPage, animate);
if (_currentModalNavPage != null)
_currentModalNavigation = _currentModalNavPage.Navigation;
}
private async void _currentModalNavPage_Popped(object sender, NavigationEventArgs e)
{
if (_currentModalNavPage != null && _currentModalNavPage.CurrentPage is FirstEmptyNavPage)
{
_currentModalNavPage.Popped -= _currentModalNavPage_Popped;
_currentModalNavPage = null;
_currentModalNavigation = null;
await _mainNavigation.PopModalAsync(false);
}
}
public async Task PopAsync(bool animate = true)
{
if (_currentModalNavigation != null && _currentModalNavigation.NavigationStack.Count > 1)
await _currentModalNavigation.PopAsync(animate);
else if (_currentModalNavigation != null && _currentModalNavigation.NavigationStack.Count > 1)
{
await _currentModalNavigation.PopModalAsync(animate);
_currentModalNavigation = null;
}
else if (_currentTabNavigation != null)
await _currentTabNavigation.PopAsync(animate);
else if (_mainNavigation != null)
await _mainNavigation.PopAsync(animate);
}
public async Task PopModalAsync(bool animate = true)
{
if (_currentModalNavigation != null)
{
await _currentModalNavigation.PopModalAsync(animate);
_currentModalNavigation = null;
}
}
}
I trying to scan QR-codes in my app. It works sometimes and sometimes not. The feeling is that it doesn't work when something is loading on another thread. For example, if I press the scan button when nearby stores still are loading. Often it works if I wait.
The video capture is working because I will see the preview.
Here is my code:
private bool resultFound;
public ScannerView()
{
InitializeComponent();
On<Xamarin.Forms.PlatformConfiguration.iOS>().SetUseSafeArea(false);
view = new UIView();
ScannerArea.Children.Add(view);
}
void HandleAVRequestAccessStatus(bool accessGranted)
{
if (!accessGranted)
{
MainThread.BeginInvokeOnMainThread(async () =>
{
await NavigationHelper.Current.CloseModalAsync();
});
}
metadataOutput = new AVCaptureMetadataOutput();
var metadataDelegate = new MetadataOutputDelegate();
metadataOutput.SetDelegate(metadataDelegate, DispatchQueue.MainQueue);
session = new AVCaptureSession();
camera = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video).First();
input = AVCaptureDeviceInput.FromDevice(camera);
session.AddInput(input);
session.AddOutput(metadataOutput);
metadataOutput.MetadataObjectTypes = AVMetadataObjectType.QRCode | AVMetadataObjectType.EAN8Code | AVMetadataObjectType.EAN13Code;
metadataDelegate.MetadataFound += MetadataDelegate_MetadataFound;
camera.LockForConfiguration(out var error);
camera.VideoZoomFactor = 2;
camera.UnlockForConfiguration();
layer = new AVCaptureVideoPreviewLayer(session);
layer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
layer.MasksToBounds = true;
layer.Frame = UIApplication.SharedApplication.KeyWindow.RootViewController.View.Bounds;
view.Layer.AddSublayer(layer);
session.StartRunning();
}
protected override void OnAppearing()
{
base.OnAppearing();
var status = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
if (status != AVAuthorizationStatus.Authorized)
{
MainThread.BeginInvokeOnMainThread(() =>
{
AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, HandleAVRequestAccessStatus);
});
return;
}
HandleAVRequestAccessStatus(true);
}
protected override void OnDisappearing()
{
base.OnDisappearing();
session.StopRunning();
session.RemoveInput(input);
session = null;
}
void Handle_Clicked(object sender, System.EventArgs e)
{
NavigationHelper.Current.CloseModalAsync();
}
void MetadataDelegate_MetadataFound(object sender, AVMetadataMachineReadableCodeObject e)
{
if (resultFound)
{
return;
}
resultFound = true;
var text = e.StringValue;
Device.BeginInvokeOnMainThread(async () =>
{
Vibration.Vibrate(100);
await NavigationHelper.Current.CloseModalAsync();
TinyPubSub.Publish(NavigationParameter.ToString(), text);
});
}
}
public class MetadataOutputDelegate : AVCaptureMetadataOutputObjectsDelegate
{
public override void DidOutputMetadataObjects(AVCaptureMetadataOutput captureOutput, AVMetadataObject[] metadataObjects, AVCaptureConnection connection)
{
foreach (var m in metadataObjects)
{
if (m is AVMetadataMachineReadableCodeObject)
{
MetadataFound(this, m as AVMetadataMachineReadableCodeObject);
}
}
}
public event EventHandler<AVMetadataMachineReadableCodeObject> MetadataFound = delegate { };
}
I want to customize my picker. I created a custom renderer for my picker but I dont know how the customization settings. How can I change the font style and size of the item? and How can I remove the two lines?
public class CustomPickerRenderer : PickerRenderer
{
public CustomPickerRenderer(Context context) : base(context)
{
AutoPackage = false;
}
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
Control.Background = null;
var layoutParams = new MarginLayoutParams(Control.LayoutParameters);
layoutParams.SetMargins(0, 0, 0, 0);
Control.LayoutParameters = layoutParams;
Control.SetPadding(0, 0, 0, 0);
SetPadding(0, 0, 0, 0);
}
}
}
If you want to set the fontSize of the text , you first need to customize a subclass extends from NumberPicker and overwrite the method AddView.
public class TextColorNumberPicker: NumberPicker
{
public TextColorNumberPicker(Context context) : base(context)
{
}
public override void AddView(View child, int index, ViewGroup.LayoutParams #params)
{
base.AddView(child, index, #params);
UpdateView(child);
}
public void UpdateView(View view)
{
if ( view is EditText ) {
//set the font of text
((EditText)view).TextSize = 8;
}
}
}
If you want to remove the lines,you should rewrite the NumberPicker
in Android Custom Renderer
public class MyAndroidPicker:PickerRenderer
{
IElementController ElementController => Element as IElementController;
public MyAndroidPicker()
{
}
private AlertDialog _dialog;
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (e.NewElement == null || e.OldElement != null)
return;
Control.Click += Control_Click;
}
protected override void Dispose(bool disposing)
{
Control.Click -= Control_Click;
base.Dispose(disposing);
}
private void SetPickerDividerColor(TextColorNumberPicker picker)
{
Field[] fields = picker.Class.GetDeclaredFields();
foreach (Field pf in fields)
{
if(pf.Name.Equals("mSelectionDivider"))
{
pf.Accessible = true;
// set the color as transparent
pf.Set(picker, new ColorDrawable(this.Resources.GetColor(Android.Resource.Color.Transparent)));
}
}
}
private void Control_Click(object sender, EventArgs e)
{
Picker model = Element;
var picker = new TextColorNumberPicker(Context);
if (model.Items != null && model.Items.Any())
{
picker.MaxValue = model.Items.Count - 1;
picker.MinValue = 0;
picker.SetBackgroundColor(Android.Graphics.Color.Yellow);
picker.SetDisplayedValues(model.Items.ToArray());
//call the method after you setting DisplayedValues
SetPickerDividerColor(picker);
picker.WrapSelectorWheel = false;
picker.Value = model.SelectedIndex;
}
var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical };
layout.AddView(picker);
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, true);
var builder = new AlertDialog.Builder(Context);
builder.SetView(layout);
builder.SetTitle(model.Title ?? "");
builder.SetNegativeButton("Cancel ", (s, a) =>
{
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
_dialog = null;
});
builder.SetPositiveButton("Ok ", (s, a) =>
{
ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value);
// It is possible for the Content of the Page to be changed on SelectedIndexChanged.
// In this case, the Element & Control will no longer exist.
if (Element != null)
{
if (model.Items.Count > 0 && Element.SelectedIndex >= 0)
Control.Text = model.Items[Element.SelectedIndex];
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is also possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
}
_dialog = null;
});
_dialog = builder.Create();
_dialog.DismissEvent += (ssender, args) =>
{
ElementController?.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
};
_dialog.Show();
}
}
I also used this CustomRenderer which was posted before only instead of overriding it you can change the properties like this.
private void Control_Click(object sender, EventArgs e)
{
Picker model = Element;
var picker = new MyNumberPicker(Context);
if (model.Items != null && model.Items.Any())
{
// set style here
picker.MaxValue = model.Items.Count - 1;
picker.MinValue = 0;
picker.SetBackgroundColor(Android.Graphics.Color.Transparent);
picker.SetDisplayedValues(model.Items.ToArray());
//call the method after you setting DisplayedValues
SetPickerDividerColor(picker);
picker.WrapSelectorWheel = false;
picker.Value = model.SelectedIndex;
// change Text Size and Divider
picker.TextSize = 30;
picker.SelectionDividerHeight = 1;
}