Tags

,

Often we feel bored with the classic Android Layout finder, the most famous FindViewById() guy. To overcome this recently I found a solution, a Xamarin component called Genetics. This is annotation based DI library and quite easy to use.

To use this, you need to add the component and follow the example. Here is a very simplified version of the same example,

using Android.App;
using Android.Widget;
using Android.OS;
using Genetics.Attributes;
using Genetics;
using System;

namespace GeneInjectTest
{
    [Activity(Label = "GeneInjectTest", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        [SpliceClick(Resource.Id.myButton)]
        private void MyButtonClicked(object sender, EventArgs e)
        {
            Toast.MakeText(this, "ButtonPressed!", ToastLength.Short).Show();
        }
        
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            Geneticist.Splice(this);
        }
    }
}

The beauty is, you do need to initialize a button – yeah thats why we use DI in general. But if you need to initialize a button all you need is to call

[Splice(Resource.Id.myButton)]
private Button myButton;

simple nah.

Also this provides make more possibilities as documented. Keep exploring and happy coding.

Advertisements