Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set an android id attribute in Xamarin.Forms?

I need to access the views created by Xamarin.Forms outside of the shared Xamarin.Forms code.

how to set an android id attribute in Xamarin.Forms?

like image 969
robotmaker01 Avatar asked Jan 16 '15 13:01

robotmaker01


1 Answers

one way of getting at the Android id is via a custom renderer. For instance, in case the view in question would be a Xamarin.Forms.Editor, you could add a custom renderer to your app as follows:

First, in your Xamarin.Forms project, add a class that derives from the view you'd like to get the id from:

namespace MyApp
{
    public class CustomEditor : Editor
    {
    }
}

Note that this class doesn't add any new members, it's just there to define a new type that we will need to associate the custom renderer with.

Then, in your Xamarin Android project, add the custom renderer and associate it with your custom view type:

using System;
using MyApp;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;


[assembly: ExportRenderer(typeof(CustomEditor), typeof(CustomEditorRenderer))]

namespace MyApp.Android
{
    class CustomEditorRenderer : EditorRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Editor> e)
        {
            base.OnElementChanged(e);

            int androidId = this.Id; // android widget id
            Guid xamarinId = e.NewElement.Id; // xamarin view id

        }
    }

Within that custom renderer you have now access to the underlying Android widget that is associated with the Xamarin Forms view. This means you can get at the Android .id property as well.

Please note:

  • for this to work, in your Xamarin.Forms UI, you'll need to use your CustomEditor instead of the stock Editor class
  • not all Xamarin Forms views have custom renderers that you can derive from. Some, like ListViewRenderer are internal classes and do not support inheriting in your code. In these cases you cannot use this technique.
like image 85
wolkenjager Avatar answered Oct 28 '22 10:10

wolkenjager