In XAMARIN FORMS ButtonRenderer only provide two methods which i can override: OnElementChanged and OnElementPropertyChanged. Which method do I want to override to handle button clicks?
You have a reference to the button in your Renderer (search for the proeprty Control). Just add the click-event/listener/command for this Control (but be carefull, it may be that the Control is NULL, depending on your renderer implementation).
Quick code sample for ios (depends on your renderer):
protected override void OnElementChanged(ElementChangedEventArgs<MyButtonRenderer> e)
{
var mybutton = Control as UIButton;
mybutton.TouchUpInside += (s, args) => { /* your logic */};
}
For android you can find a sample on this page.
Related
So I have the following code:
<TabBar Route="Dashboard">
<Tab Title="Dashboard" AutomationId="DashboardId">
//more codes here
</Tab>
<Tab AutomationId="AddNewId">
//more codes here
</Tab>
<Tab Title="Statistics" AutomationId="StatisticsId">
//more codes here
</Tab>
</TabBar>
Note that in my MainActivity's OnCreate() I have set up the following:
Xamarin.Forms.Forms.ViewInitialized += (object sender, Xamarin.Forms.ViewInitializedEventArgs e) => {
if (!string.IsNullOrWhiteSpace(e.View.AutomationId))
{
e.NativeView.ContentDescription = e.View.AutomationId;
}
};
This works perfectly with my other elements except for the TabBar items. Somehow the TabBar items are getting the Title property and setting is at the accessibilityId/content-dec.
Anyone knows why this is and how can I make it so it will get the right AutomationId? Thanks
There are multiple issues with AutomationId on Android.
The underlying problem is discussed in Android - Using AutomationId prevents TalkBack screenreader accessibility:
Xamarin.Forms "borrows" the ContentDescription property on Android for Automation IDs. These IDs polute Android's TalkBack accessibility tree, making apps almost impossible to navigate.
This means you can support test automation or accessibility, not both. Our app needs to support both.
In the case of Tabs, presumably Xamarin code is doing what you see: copying Title to content-desc, so that Android text readers will speak it.
The suggested work-around is to write custom renderer(s) that do what you need. Described in a comment by codingL3gend :
i was able to find a work around to this issue by creating a customrenderer and respective custom component to allow for overriding the native android method(s) that get triggered when accessibility events are fired. you will need to create some bindable properties on your custom component that you can access in the custom renderer to allow for setting the content description value to what you want but that's simple enough.
this method gets triggered in the control/custom renderer whenever an accessibility event is fired
public override bool OnRequestSendAccessibilityEvent(Android.Views.View child, AccessibilityEvent e)
{
if (AccessibilityHandler.IsAccessibilityEnabled(_context) && child != null)
{
if (!string.IsNullOrEmpty(_automationId) && _automationId.Equals(child.ContentDescription))
{
child.ContentDescription = $"{_automationName} {_helpText}";
}
}
return base.OnRequestSendAccessibilityEvent(child, e);
}
then you can set the contentDescription value of the control/custom renderer back to what the automationId value was originally when the control/custom renderer is detached from the view.
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
if (!string.IsNullOrEmpty(_automationId))
{
Control.ContentDescription = _automationId;
}
}
helper class
public static class AccessibilityHandler
{
public static bool IsAccessibilityEnabled(Context context)
{
var accessibility = (AccessibilityManager)context.GetSystemService(MainActivity.AccessibilityService);
return accessibility?.GetEnabledAccessibilityServiceList(Android.AccessibilityServices.FeedbackFlags.Spoken)?.Count > 0;
}
}
If you only need AutomationId during testing, or you can live with the effect this has on Accessibility Screen Readers (esp. it won't be multi-lingual), then you could make a much simpler custom renderer for use when testing.
Put this in your custom renderer (if isn't Tab, then change <Tab> to appropriate Xamarin class):
protected override void OnElementChanged( ElementChangedEventArgs<Tab> e )
{
base.OnElementChanged( e );
if (e.OldElement != null)
{
// Removing previous element.
// TBD: Remove obsolete references. (usually not needed)
}
if (Element == null)
// Going away with no replacement.
return;
UpdateAutomationId();
}
void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Element.AutomationId))
{
UpdateAutomationId();
}
}
void UpdateAutomationId()
{
var _automationId = Element.AutomationId;
if (!string.IsNullOrEmpty(_automationId))
{
Control.ContentDescription = _automationId;
}
}
I have created a forms page in Xamarin and used that page as a fragment using Xamarin Forms Embedding.
var fragment = new FormsPage().CreateFragment(context);
I would like to override the OnBackPressed() control in Android version of the app.
What's the best possible way to do it as I can't override it inside the Xamarin Forms Page.
I would like to override the OnBackPressed() control in Android version of the app.
You could override OnBackButtonPressed in Xamarin.Forms, this event also be raised when the hardware back button is pressed in Android and this event is not raised on iOS.
If you want remove fragment from the stack in OnBackPressed() method, you could override this method in your Activity like this :
public override void OnBackPressed()
{
base.OnBackPressed();
if (FragmentManager.BackStackEntryCount != 0)
{
FragmentManager.PopBackStack();
}
else
{
base.OnBackPressed();
}
}
In my Xamarin app, I create a button (Xamarin.Forms.Button) programmatically. I need this button to show a different background image under normal vs hovered state. I have created a style resource similar to what is described at How to indicate currently selected control in Xamarin?. However, I cannot figure out how to apply this style to the button.
The Button class exposes a property called Image that is of FileImageSource type. The closest API I found to load my style resource is ImageSource.FromResource static method. However, this method seems to return StreamImageSource instance which is not what we need.
Class Button does not seem to provide any Style property.
Can you please suggest how I can programmatically associate a style to the button? Regards.
To achieve this request you need custom renderers.
To be able to apply your style f.e.: "myButtonStyle.xml" you have to create a custom renderer for your target platform:
Android:
[assembly: ExportRenderer (typeof (YourExtendedButtonClass), typeof (MyCustomButtonRenderer))]
namespace YourApp.Droid
{
public class MyCustomButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
var myButton = this.Control as Android.Widget.Button;
myButton?.SetBackgroundResource(Resource.Drawable.myButtonStyle);
}
}
}
How do you change the font of the 'spinner' portion of the picker? I can change the display font doing the following
public class MyPickerRenderer : PickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
if (Control != null)
{
**Control.Font = UIFont.SystemFontOfSize(8);**
}
}
}
Unfortunately this is not possible at least it's not subclassing the PickerRenderer defined in Xamarin.Forms for iOS.
The UIPickerView control that is displayed is marked as private for the renderer implementation, hence it will not be accesible from the subclass.
You could anyway do your own implementation of the Renderer and for this you could follow the implementation made by Xamarin.Forms (here you can see it) and do the modifications you need.
You will also need to subclass the UIPickerView class and override the ViewFor and there set the font size you want for the items..
Hope this helps.-
I'm currently in the process of developing a SideDrawer for Xamarin.Forms, because at this point, the one from telerik is rather awful sideeffect-wise.
I know how to do this in WPF, since it's rather easy, but in Xamarin it's way different.
My code for the GestureFrame is pretty much the same as this.
I've used the sources at some github project/xamarin docs/XLabs to get started. At first it was going well, but as soon as i'm placing controls within the gestureframe i will not receive any events anymore, because the childcontrols appear to consume any touch/gesture events there are.
Does this ring a bell to anyone? Right now i'm not sure what i might be doing wrong for the control to behave this way
The Only Gestures that Xamarin Forms handles currently are Tap and DoubleTap these bubble up by default. For Android, Windows and presumably IOS each handle other gestures differently.
Quick Review of Event Handling in the Xamarin.Forms world:
On Android
Gestures are handled by the Renderer each renderer has a Touch event. Touch is raised in the renderer when a gesture occurs. By subscribing to the Touch event and intupreting the EventArgs you can determine what is happening on the screen. Now you could make all the determinations yourself of what the user is doing or use the Mono.Android.GestureDetector to make those decisions for you. GestureDetector requires a GestureListener which it notifies when it believes an event like a tap or double have occured. Your Gesture listener can then contain whatever code you want to respond to these events.
On Windows
Each native control determines for itself When an event has occurred and exposes a set of EventHandlers for those events. To respond to these events you create a custom renderer and subscribe to the events on the native controls that then execute your own code.
On IOS?
Don't know yet haven't got that far in my project https://github.com/Indiponics/IndiXam-Lib maybe someone else can give you that piece.
Bubbling up the Events
Lets look at a simple bubbling situation:
public class App : Application
{
public App()
{
// The root page of your application
MainPage = new ContentPage
{
Content = new Frame
{
Content =
new Label {
Text = "Hold Me, Thrill Me, Kiss Me"
}
}
};
}
}
Lets put some Custom Renderers together and look at whats happening. To start with we'll need a renderer for every control in the stack so in our case a Label Renderer and a Frame Renderer.
We'll Start with Windows:
[assembly: ExportRenderer(typeof(Label), typeof(myLabelCustomRenderer))]
[assembly: ExportRenderer(typeof(Frame), typeof(myFrameCustomRenderer))]
namespace App4.WinPhone
{
public class myFrameCustomRenderer:FrameRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Frame> e)
{
base.OnElementChanged(e);
if(e.NewElement!=null)
{
this.Control.Hold += Control_Hold;
}
}
void Control_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Frame Held");
e.Handled = false;
}
}
public class myLabelCustomRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Label> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
this.Control.Hold += Control_Hold;
}
}
void Control_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Label Held");
e.Handled = false;
}
}
}
Running this we find that
Bubbling actually occurs by default in windows. If we wanted we could turn off bubbling by changing
e.Handled = true;
In our Label Renderer and the frame would never get notified of the Hold Event.
Now For Android
On Android things get a bit messier. Again we'll create two renderers.
[assembly: ExportRenderer(typeof(Label), typeof(myLabelCustomRenderer))]
[assembly: ExportRenderer(typeof(Frame), typeof(myFrameCustomRenderer))]
namespace App4.Droid
{
public class myFrameCustomRenderer : FrameRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Frame> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
this.Touch += myFrameCustomRenderer_Touch;
}
}
void myFrameCustomRenderer_Touch(object sender, Android.Views.View.TouchEventArgs e)
{
System.Diagnostics.Debug.WriteLine("You Touched My Frame");
e.Handled = false;
}
}
public class myLabelCustomRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Label> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
this.Touch += myFrameCustomRenderer_Touch;
}
}
void myFrameCustomRenderer_Touch(object sender, Android.Views.View.TouchEventArgs e)
{
System.Diagnostics.Debug.WriteLine("You Touched My Label");
e.Handled = false;
}
}
}
If we run this it appears that everything works the same as windows we geta touch event in the label and a touch event in the Frame. The bubbling up appears to be automatic. It Gets messy when we attempt to disable bubbling. If we change
e.Handled=true;
in the Label Renderer and run the app again---
Touch fires twice IN THE LABEL RENDERER. Once for when we touch the screen and once for when we stop. If we set the labelrenderer's e.Handled=false; and set the Frame to true. Then the label touch fires followed by the Frame but only the Frame Fires the second time.
In addition if we remove e.Handled=false from both renderer and run the app we find that only the LabelRenderer's Touch event fires. Implying that the default for Handled appears to be true. If you do not set e.Handled=false in the renderer the event will fire in the LabelRenderer and not bubble up the stack to the FrameRenderer.
In Conclusion:
Bubbling works out of the box on Windows. On Android it doesn't work like you might expect. First you have to explicitly set the Handled=false in every child so the parent gets notification and even then only the Handler that Handled the event gets notified that the touch event ended the rest of the stack gets notified of the start but never knows its over.