On Android MainDisplayInfoChanged event doesn't trigger on RequestedOrientation - xamarin

I'm trying to implement a mediaplayer in Xamarin.Forms, and to make a full screen function I've added a button which toggles the device between landscape and portrait. This works fine, but for some reason my android device doesn't trigger the DeviceDisplay.MainDisplayInfoChanged event until I actually flip the phone to match the new orientation.
So the app DOES change orientation, but doesn't fire the event until I physically flip my phone. This is happening on a physical device.
On iOS this works fine, so I'm a little confused.
My shared code on the video player page:
private void VideoControlView_ToggleFullScreen(object sender, EventArgs e)
{
if (_isFullScreen)
DependencyService.Get<IOrientationService>().SetOrientationToPortrait();
else
DependencyService.Get<IOrientationService>().SetOrientationToLandscape();
}
private async void DeviceDisplay_MainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
if (AutoRotateDisabled)
return;
await DisplayVideoFullScreen(e.DisplayInfo.Orientation == DisplayOrientation.Landscape);
}
And my service to change the orientation for android:
public class OrientationService : IOrientationService
{
public void SetOrientationToLandscape()
{
((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Landscape;
}
public void SetOrientationToPortrait()
{
((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Portrait;
}
}
And for iOS just in case:
public class OrientationService : IOrientationService
{
private const string ORIENTATION_KEY = "orientation";
public void SetOrientationToLandscape()
{
SetOrientation(UIInterfaceOrientation.LandscapeRight);
}
public void SetOrientationToPortrait()
{
SetOrientation(UIInterfaceOrientation.Portrait);
}
public void SetOrientation(UIInterfaceOrientation orientation)
{
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)orientation), new NSString(ORIENTATION_KEY));
}
}
To recap:
When I trigger my ToggleFullScreen event, my android device corrently enters landscape mode, but it does NOT trigger MainDisplayInfoChanged.
I have tested this on two different physical android devices with the same issue.
Any help is appreciated, thanks!

Related

How to detect backspace in an Entry control when it is empty

I am using Xamarin.Forms with Android. I have a form which has 4 Entry controls for a user to enter code. I am using TextChanged event to detect user input and automatically move focus to the next control. This part works fine, i.e. as user types a digit focus automatically jumps to the next entry. However, I need to achieve the opposite, user should be able to tap backspace button and focus should move to the previous control. The problem is that TextChanged is not triggered when entry control is empty. How can I achieve this? Is there a custom renderer I can create for android to capture text input? Maybe there is a way to use 1 entry instead but I need to make it look like distinct 4 boxes.
Finally,I've found a solution for this by implementing a renderer in android.
In shared code(PCL),Create a class like this
public class CustomEntry:Entry
{
public delegate void BackspaceEventHandler(object sender, EventArgs e);
public event BackspaceEventHandler OnBackspace;
public CustomEntry()
{
}
public void OnBackspacePressed()
{
if (OnBackspace != null)
{
OnBackspace(null, null);
}
}
}
And,Then in your android project create a renderer like this:
public class CustomEntryRenderer: EntryRenderer
{
public override bool DispatchKeyEvent(KeyEvent e)
{
if (e.Action == KeyEventActions.Down)
{
if (e.KeyCode == Keycode.Del)
{
if (string.IsNullOrWhiteSpace(Control.Text))
{
var entry = (PasswordBox)Element;
entry.OnBackspacePressed();
}
}
}
return base.DispatchKeyEvent(e);
}
protected override void
OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
}
}
And then use it like this:
Entry1.OnBackspace += Entry1BackspaceEventHandler;
public void Entry1BackspaceEventHandler()
{
//things you want to do
}

How do I enable WebGL in Xamarin.Forms WebView on UWP?

I’m new to Xamarin.Forms and tried using WebView on my Windows 10 x64 v1803 machine with UWP but I can’t see how to get it to work with WebGL.
Sites which use WebGL either display a message that “Your video card does not support WebGL or just don’t display and graphical content at all.
Is this a limitation of UWP or WebView itself?
Is it a WebView configuration issue?
WebGL works in all other browsers on this machine.
UWP WebView control is support WebGL. There is similar issue case in msdn you could refer. Please try to use SeparateProcess mode WebView to replace the default one.
public MainPage()
{
this.InitializeComponent();
var MyWebView = new WebView(WebViewExecutionMode.SeparateProcess);
MyWebView.Source = new Uri("http://cycleblob.com/");
this.RootGrid.Children.Add(MyWebView);
}
I had the same problem, but with the newer Xamarin Forms it took a little more poking around to get this took work right. However, I do like that they moved the native WebView resolver back to the responsibility of the UWP/iOS/Android project (as a native XAML object) instead of using code branching with compiler directives in the Shared project.
Start by creating a HybridWebView class in the shared project to use as your WebForm view object:
public class HybridWebView : Xamarin.Forms.WebView
{
Action<string> action;
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(HybridWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
public void RegisterAction(Action<string> callback)
{
action = callback;
}
public void Cleanup()
{
action = null;
}
public void InvokeAction(string data)
{
if (action == null || data == null)
{
return;
}
action.Invoke(data);
}
}
Then in the UWP project, create a custom renderer, which will construct the native WebView and relay the events back to the WebForms object in the Shared project:
Put this at the top of the namespace, to link the HybridWebView with the Custom Renderer:
[assembly: ExportRenderer(typeof(HybridWebView), typeof(WebViewRenderer2))]
Then create the renderer class (for the IOS and android projects, if you leave this class out, it defaults to the standard native controls which seem to work fine for me):
public class WebViewRenderer2 : ViewRenderer<Xamarin.Forms.WebView, Windows.UI.Xaml.Controls.WebView>, IWebViewDelegate
{
Windows.UI.Xaml.Controls.WebView _control;
public void LoadHtml(string html, string baseUrl)
{
}
public void LoadUrl(string url)
{
}
protected override void Dispose(bool disposing)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
if (_control == null) {
_control = new Windows.UI.Xaml.Controls.WebView(WebViewExecutionMode.SeparateProcess);
SetNativeControl(_control);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var xamWebView = sender as HybridWebView;
switch(e.PropertyName.ToLower())
{
case "source":
var urlSource = xamWebView.Source as Xamarin.Forms.UrlWebViewSource;
_control.Source = new Uri(urlSource.Url);
break;
case "width":
_control.Width = xamWebView.Width;
break;
case "height":
_control.Height = xamWebView.Height;
break;
case "isfocused":
var focused = xamWebView.IsFocused;
if (focused)
_control.Focus(FocusState.Programmatic);
else
_control.Focus(FocusState.Unfocused);
break;
}
}
}
You can also use the Custom Renderer to inject scripts, and you can use it to communicate from the native webview back to the Xamarin App, as seen here: HybridWebView Communication

How do I listen to UWP Xaml Slider manipulation start/end events?

What events should I listen to on a UWP Xaml Slider to determine when the user begins and ends manipulation.
This functionality is important when you have a slider that represents some continuously changing app state (say, an animation time) and you want to pause the update when the user interacts with the slider.
This question has been answered for WPF and Windows Phone, but not UWP. The other solutions do not work, or are incomplete, for UWP.
You need to listen to interaction events from a couple of the elements of the Slider template: the Thumb, and the Container. This is because the user can manipulate the thumb directly by clicking and dragging it, but also they can click anywhere on the slider and the thumb will jump to that location (even though it looks like you are then manipulating the Thumb, actually the thumb is just being relocated every time the mouse moves - you are still interacting with the container).
There are a couple caveats:
the thumb and container both process their input events and do not pass them on, so you need to use the AddHandler method of attaching RoutedEvent handlers so that you get events which have already been processed.
you need to attach the event handlers after the control template has been applied, which means you need to subclass the Slider to override a protected method.
The RoutedEvent handler information is covered here: https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/events-and-routed-events-overview#registering-handlers-for-already-handled-routed-events
The following SliderEx class adds some events which can be used to detect when the user begins/ends interacting with the slider:
public class SliderEx : Slider
{
public event EventHandler SliderManipulationStarted;
public event EventHandler SliderManipulationCompleted;
public event EventHandler SliderManipulationMoved;
private bool IsSliderBeingManpulated
{
get
{
return this.isContainerHeld || this.isThumbHeld;
}
}
private bool isThumbHeld = false;
private bool isContainerHeld = false;
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
var thumb = base.GetTemplateChild("HorizontalThumb") as Thumb;
if (thumb == null)
{
thumb = base.GetTemplateChild("VerticalThumb") as Thumb;
}
if (thumb != null)
{
thumb.DragStarted += this.Thumb_DragStarted;
thumb.DragCompleted += this.Thumb_DragCompleted;
thumb.DragDelta += this.Thumb_DragDelta;
}
var sliderContainer = base.GetTemplateChild("SliderContainer") as Grid;
if (sliderContainer != null)
{
sliderContainer.AddHandler(PointerPressedEvent,
new PointerEventHandler(this.SliderContainer_PointerPressed), true);
sliderContainer.AddHandler(PointerReleasedEvent,
new PointerEventHandler(this.SliderContainer_PointerReleased), true);
sliderContainer.AddHandler(PointerMovedEvent,
new PointerEventHandler(this.SliderContainer_PointerMoved), true);
}
}
private void SliderContainer_PointerMoved(object sender,
Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{
this.InvokeMove();
}
private void SliderContainer_PointerReleased(object sender,
Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{
this.SetContainerHeld(false);
}
private void SliderContainer_PointerPressed(object sender,
Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{
this.SetContainerHeld(true);
}
private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
{
this.InvokeMove();
}
private void Thumb_DragCompleted(object sender, DragCompletedEventArgs e)
{
this.SetThumbHeld(false);
}
private void Thumb_DragStarted(object sender, DragStartedEventArgs e)
{
this.SetThumbHeld(true);
}
private void SetThumbHeld(bool held)
{
bool wasManipulated = this.IsSliderBeingManpulated;
this.isThumbHeld = held;
this.InvokeStateChange(wasManipulated);
}
private void SetContainerHeld(bool held)
{
bool wasManipulated = this.IsSliderBeingManpulated;
this.isContainerHeld = held;
this.InvokeStateChange(wasManipulated);
}
private void InvokeMove()
{
this.SliderManipulationMoved?.Invoke(this, EventArgs.Empty);
}
private void InvokeStateChange(bool wasBeingManipulated)
{
if (wasBeingManipulated != this.IsSliderBeingManpulated)
{
if (this.IsSliderBeingManpulated)
{
this.SliderManipulationStarted?.Invoke(this, EventArgs.Empty);
}
else
{
this.SliderManipulationCompleted?.Invoke(this, EventArgs.Empty);
}
}
}
}

Simple navigation in Windows 8 web view

I'm working on porting a Windows Phone 8 application to tablet, and I've bumped into a problem with the WebView API. In Windows Phone 8 and Windows 8.1, the WebBrowser and WebView controls both have a GoBack() method. However, I need my application to be compatible for Windows 8, whose WebView API does not have such a method. Are there any alternatives/workarounds that anyone's used for Windows 8 apps?
In the end I just ended up writing a wrapper for the WebView to manage the navigation stack. Here's the relevant code, for anyone who's interested. Note that I only needed to handle backwards navigation, so I used a Stack. If forwards navigation is also required, it'd probably make sense to replace the Stack with a List and store the index of the current page instead.
public class WebViewWrapper
{
private Stack<Uri> _navigationStack;
private Uri _currentUri;
public WebView WebView { get; private set; }
public bool CanGoBack
{
get { return _navigationStack.Count > 0; }
}
public WebViewWrapper(WebView _webView)
{
_navigationStack = new Stack<Uri>();
WebView = _webView;
WebView.LoadCompleted += (object s, NavigationEventArgs e) => {
if (_currentUri != null)
{
_navigationStack.Push(_currentUri);
}
_currentUri = e.Uri;
};
}
public void GoBack()
{
if (CanGoBack)
{
_currentUri = null;
WebView.Navigate(_navigationStack.Pop());
}
}
}
An example of usage would be as follows:
// Code behind for a view called WebBrowserPage
public sealed partial class WebBrowserPage : Page
{
private WebViewWrapper _webViewWrapper;
public WebBrowserPage()
{
// webView is a WebView in the xaml with x:Name="webView"
_webViewWrapper = new WebViewWrapper(webView);
}
// Other code for navigating to a Uri specified in a ViewModel.
// Event handler for a back button press
private void BackButton_Click(object sender, RoutedEventArgs e)
{
if (_webViewWrapper.CanGoBack)
{
_webViewWrapper.GoBack();
}
else
{
// Code that executes a command in the ViewModel to leave the WebBrowserPage
}
}
}
WinRT XAML Toolkit has a WebBrowser control that does some of that, but I haven't used it in any app, so I can't vouch for its quality.

Need help using the CameraCaptureTask

i am trying to create a simple demo application that does the following: i have a button at MainPage.xaml (with Name="btnCamera") and an image control (with Name="photo") and when i press the button i want to start the camera task, capture a photo and display it on the image control. The problem is that my code works on the emulator but not on a real device. The device i have is updated to the latest update(7740). Do you have an explanation for that or any change to my code to make it work? That is my code:
public partial class MainPage : PhoneApplicationPage
{
CameraCaptureTask _cameraCapture;
public MainPage()
{
InitializeComponent()
_cameraCapture = new CameraCaptureTask();
_cameraCapture.Completed += new EventHandler(_cameraCapture_Completed);
}
private void btnCamera_Click(object sender, RoutedEventArgs e)
{
try
{
_cameraCapture.Show();
}
catch (Exception)
{
MessageBox.Show("Error occured");
}
}
void _cameraCapture_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
photo.Source = image;
}
}
}
You need to make sure Zune is not running. The code looks fine and should work if you unplug the phone from the PC. If you want to debug whilst plugged into the PC, use WPConnect instead of Zune.

Resources