Corrado's Blog 2.0

Online thoughts of a technology funatic

Genymotion and VirtualBox install issue

I use Genymotion as Android emulator for my Xamarin work, I know that there are better alternatives like Microsoft’s Android emulator but since can’t turn on Hyper-V on my machine this is the solution that works best for me.

Haven’t done any Android development recently so since I need to prepare some demos for my forthcoming session at Future Decoded I checked my system and discovered that Android emulator wasn’t working anymore as happened in the past. Checked the logs but nothing evident was listed apart some in influent login error, I then tried to run VirtualBox alone and noted that it was not starting at all, no error nor messages, just nothing was happening.

Ok, let’s reinstall Genymotion to latest version, maybe recent Windows 10 Anniversay update broke something, did that, no errors but, nothing changed, ok, let’s try installing VirtualBox alone from Oracle site and BOOM! got a weird error message about an adapter not being created because it was not possible to rename it (WHAAAT?)

Fired up a search engine looking for solutions and found thousands of thread starting from 2010, some of them even suggesting to repave the entire machine, luckily among this tons of documentation my attention got catched by a guy that claimed to have solved using this steps:

  1. 1-Go to 
  2. C:\Program Files\Oracle\VirtualBox\drivers\network
    2-Go into each directory contained into network and install the drivers by tight clicking every .inf file and selection Install from popup menu


    3-Go to Network Connections, right click the Ethernet adapter associated with VirtualBox and select Properties


    4-On the network properties panel, click Install and select Services


    5-Now select the Oracle’s VirtualBox driver and select OK


    6-Be sure that VirtualBox NDIS driver is selected.


    7-Complete Genymotion install, if not already done, otherwise, just download a device and runt it, if it is your lucky day, it should work.

    You can read the original answer here, it also worked for me of course.

    …and after this annoying procedure you can go back coding in relax. Smile


    A Smart RecyclerView Adapter for Xamarin.Android

    RecyclerView is the recommended way to represents a collection of items in Android applications, the good and old ListView is now deprecated since RecyclerView offers a lot of improvements like flexible layout, item recyclying and enforces the ViewHolder pattern.

    If you’re new to RecyclerView in Xamarin Android I recommend this article from Xamarin site, since it is also the origin project I’ve used on this post and this is not a RecyclerView tutorial.
    This post originates since every time I need to use a RecyclerView, even for simple demos like this blog post, I end up rewriting the same boilerplate code, so I decided to create a simple generic adapter that simplifies things for me.

    Source code and demo is available on GitHub here, so get it and have a look if you want to know more about the internals, I’ll just show you how to use it updaing the original Xamarin demo.

    Just create a class that inherits from abstract SmartRecyclerAdapter<T> class

    as you see, you just have to implement two methods OnLookupViewItems and OnUpdateView: OnLookupViewItems is used to extract the view items from inflated layout and save them into provided generic viewholder
    OnUpdateView is used to update the same view items with the fresh values coming from provided Item.

    Let’s see now in action, exploring the code in MainActivity:

    Very simple: I created an instance of the PhotoRecyclerAdapter passing to its constructor: the RecyclerView, an ObservableCollection<T> as item source and the optional id of the layout to inflate to create the items views (more on this later)

    Since we’re using an ObservableCollection<T> the list is smart enough to automatically invoke the several NotifyXYZ methods when you add/remove/move items from the collection as when the “Clear+Add” button of the demo is clicked.

    What if you need to use different layouts depending on items properties? just override base class GetViewIdForType method and return an int that will be passed to the othere method you’ll have to override named OnGetViewId inside this method, depending on passed viewTypeId you’ll return the item id to inflate for such element.

    The adapter automatically raises an ItemSelected event when an item is clicked, passing null as RecyclerView parameter on PhotoRecyclerAdapter constructor, disables this behavior and you can implement your own item selection strategy.

    It’s just a starting point, hope you’ll like it. Smile

    AutoHide FloatingActionButton in Xamarin.Android

    My main phone is an Android and as a news app I use a 3rd party aggregator that, al nearly all Android apps today is based on Material Design.
    Using it everyday I couldn’t ignore a nice UI feature it exposes: it’s share button (a Material Design’s FloatinActionButton) fades out when you scroll the list vertically and it reappears when you scroll the list down.
    Being curious, I wanted to know how to create that effect using Xamarin.Android.

    This is my final result:


    Since there’s a lot of setup involved I won’t go too much into code detail and setup, you can grab the project source code from here

    I’m assuming you have some basic knowledge of Material Design and  related steps to enable it into a Xamarin.Android app so and I’ll go straight to the point: The view you see is made up of a CoordinatorLayout that hosts a NestedScrollView that contains a series of CardViews and in the bottom right corner there is our FloatingActionButton.

    The trick of making it disappear is to add a custom behavior so that CoordinatorLayout knows that it has to invoke a behavior that takes care to hide/show it when something happen, in our case when user scrolls up or down.

    This is the required behavior

    Inside OnNestedStartScroll we inform the CoordinatorLayout that we want to receive scroll events when user scrolls vertically while inside OnNestedScroll we receive a reference to the FloatingActionButton (since we have applied the behavior to it) and depending on scroll direction we show/hide it.

    The hard part of migrating this code to Xamarin was fixing the weird compilation issues I was having, I thank community guy fex for giving me the hint to add the [Register] attribute at the top to the class definition and inheriting from CoordinatorLayout instead of my initial FloatingAction. No idea if this is a bug, I’ve seen someone already filed it on Bugzilla but still without any reply.

    Is now time to associate out behavior to the FloatinActionButton, I’ll do that using the standard approach to define the fully qualified path to the class inside strings.xml for better refactoring.

    and now it’s just a matter of attach it to the button

    If you use material design in your appls you’ll immediately recognize the now stanrdard elements, the only real new is the layout_behavior attribute applied to the FloatingActionButton that points to our custom behavior.

    There are indeed simpler alternatives like James Montemagno component available here but looks like it is now deprecated and I think that, once you know how to fix the ACW compilation issues, knowing how to use material design behaviors wont hurt.

    Enjoy Smile

    Add a SnackBar to you Xamarin.Android app

    Material design introduced a new lightweight way to provide feedback to a user, something that sits between the AlertDialog and Toast alternatiives with a funny name: SnackBar.
    A Snackbar appears at the bottom of the view and can optionally display an additional custom button.

    Here are the basic steps to show a SnackBar:

    -Open Visual Studio and create a new blank Android app

    -Using Nuget add the Xamarin.Android.Support.Design library, this will let you target Android releases older than v21


    • -Using the code generated by the template, lets make the SnackBar appear when the default button is pressed.

    -Add this code inside MainActivity’s OnCreate method

    protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.MyButton); button.Click += (s, e) => { //Creates the Snackbar Snackbar snackBar = Snackbar.Make(button, "Text", Snackbar.LengthIndefinite); //Show the snackbar snackBar.Show(); }; } }

    • -Compile the project and wait until build succeeds, be patient if operation takes more than than usual since this delay is due to the fact that the missing packages are downloading and their size is quite huge. If you stop compilation download will fail and you’ll start having a lot of “…invalid zip” error. in this case delete the zip folder mentioned on error message and try again.
    • -You’ll now see this error message:
    • image
    • -Let’s fix it adding the required theme (you can create your own deriving from Theme.AppCompat of course)
      [Activity(Label = "TestSnackBar2", MainLauncher = true, Icon = "@drawable/icon", Theme = "@style/Theme.AppCompat")]

    • -Run the project again and you’ll see this bar appear at the bottom of the view
    • image
    • -Quite sad indeed, luckily the SnackBar can be customized, so let’s add more code:
    button.Click += (s, e) => { //Creates the Snackbar and subscribes the button press event Snackbar snackBar = Snackbar.Make(button, "Text", Snackbar.LengthIndefinite).SetAction("Ok", (v) => { Console.WriteLine("Done"); }); //set action button text color snackBar.SetActionTextColor(Android.Graphics.Color.Green); //Set action button text size TextView txtAction = snackBar.View.FindViewById<TextView>(Resource.Id.snackbar_action); txtAction.SetTextSize(Android.Util.ComplexUnitType.Dip, 18); //Set message text size and color TextView txtMessage = snackBar.View.FindViewById<TextView>(Resource.Id.snackbar_text); txtMessage.SetTextColor(Android.Graphics.Color.Red); txtMessage.SetTextSize(Android.Util.ComplexUnitType.Dip, 12); //Show the snackbar snackBar.Show(); };

    • -And there you go, a custom SnackBar Smile
    • image

    If you’re wondering why you need to pass a reference to a view (Button in our case) as SnackBar first parameter is because internally it walks up the visual tree so that can properly position itself at bottom position.


    Xamarin.Android Status bar color not set

    Not a very descriptive title, but good for search engines Smile

    The problem: You’re using Xamarin.Android.Support.v7.AppCompat in order to have Material Design’s Toolbar available also devices running o pre-Lollipop (v.21) releases.

    You added a reference to the library:


    Added the style:

    <style name="ParentMaterialTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="colorControlHighlight">#1ef1ab</item> <item name="colorButtonNormal">#f955f3</item> <item name="colorControlActivated">#0cf427</item> </style>

    Added the entry into AndroidManifest.xml:

    <application android:label="_02_StandaloneToolbar" android:theme="@style/MaterialTheme" />

    Created the toolbar:

    < xmlns:android="" xmlns:app="" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:minHeight="?attr/actionBarSize" android:theme="@style/ToolbarTheme" app:popupTheme="@style/PopupTheme" android:id="@+id/toolbar"> </>

    Included into Main.axaml:

    <RelativeLayout xmlns:android="" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <include android:layout_width="match_parent" android:layout_height="wrap_content" layout="@layout/toolbar"/> </RelativeLayout>

    But when you run it, the status bar doesn’t follow colorPrimaryDark but it remains black Confused smile



    Solution: add this line into Activity’s OnCreate method (yes, you have to use code)


    And you’re done!


    Use IDEA IDE for Android UI design with Visual Studio and Xamarin

    While Xamarin did a monster job integrating Android and iOS designers in both Visual Studio and Xamarin Studio as soon as your project becomes larger you’ll soon hit their limitations, that why many pro developers end up using native designers for UI design. This post is about how to use IntelliJ IDEA based IDEs for Android UI design together with Visual Studio, following the same approach we use with Blend for Windows development.

    Step 1: install your favorite IDE: Android Studio or IntelliJ IDEA (they’re practically the same since Android Studio is based on IntelliJ IDEA)

    Step 2: Install XamarIdea extension for Visual Studio, this extension, recently updated for Visual Studio 2015, will make integration between the two IDEs a lot faster, thanks to Egor Bogatov (@EgorBo) for sharing.
    No idea if something similar exists for Xamarin Studio (sorry, I’m not an pro Xamarin Studio user)

    Step 3: Create a new blank Android app using Visual Studio


    and wait until initial project skeleton creation process ends.

    Step 4: Right-click the Main.axml file inside Resources\layout folder and you should see a new option: Open in IDEA/Android Studio


    click it and you’ll get an initial configuration dialog that should point to IDEA/Android Studio path, if not select it manually, together with other plugin options


    click Ok, and you’ll see a warning dialog saying that your project needs some modifications:


    These modifications are necessary since Android layout files use a different extension (.xml) and project structure is slightly different than Xamarin Android apps, just say yes; unfortunately these changes will prevent you to use the integrated Xamarin Android designer further unless you rename the layout file back to .axml. Click Yes, and you’ll get a final dialog reminding you to recompile your project inside Android IDE and that plugin options are available under Visual Studio’s Tools menu:


    Step 5: Switch to IDEA IDE and, for sure, rebuild the project


    On the left you’ll see the project structure, under app node expand the Resources folder and you’ll see the familiar Android folder structure together with your renamed main.xml file.


    Double click it to open the designer.


    I won’t go into design detail since there are lots of demo tutorials on JetBrains’s site, just want you to see some of the plus of IDEA and why it is more productive than Visual Studio’s integrated editor/designer.

    Step 5: Design

    -Select and delete the autogenerated button from design surface.
    -Let’s change root LinearLayout to a RelativeLayout using the Component tree window in the upper right corner.


    -Drag a Plain Text to design surface until top tooltip shows CenterVertical/CenterHorizontal


    -Set layout_width to match_parent using Properties window (hint: if you need to search for a property just start typing to select matching properties Smile)

    -Let use xml editor to add left and right margins: Switch to text, select the EditText and start typing: ma, YES! full intellisense to the rescue!


    -Do you want to create a style that you can reuse with others EditTexts? just right click the edit text and use Refactor –> Extract Style menu


    Select the properties you want to export (this dialog will look familiar to Reshaper users) and click OK


    the layout xml has been changed to:

    <EditText android:id="@+id/editText" style="@style/MyEditTextStyle"/>

    and a styles.xml file has been created for you under values folder:


    Of course you can edit the styles.xml file with full intellisense / editors support


    Step 6-Back to Visual Studio

    Save the project and switch back to Visual Studio, your main.xml file is automatically updated, but unfortunately the new files that have been added to the project, like styles.xml in our demo, must be added manually to the project.

    Add styles.xml under values folder, compile and continue developing your app using Visual Studio.


    I’ve just scratched the surface of IDEA design productivity features, I encourage you to give it a try, I’m sure you’ll love it.

    Have fun exploring!

    PS: Did I tell you that IDEA renders AppCompat’s widgets instead of a boring dark gray box? Winking smile

    Change ListView RowHeight programmatically in Xamarin Android

    Here’s a quick code snippet that allows you to change the row height of an Android ListView in Xamarin

    public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView ?? this.context.LayoutInflater.Inflate(Android.Resource.Layout.ActivityListItem, null); if (view.LayoutParameters == null) { view.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 300); } else { view.LayoutParameters.Height = 300; } ...other code here... return view; }

    Code resides inside ListView adapter, as you see, the magic is acting on view LayoutParameters property.

    Hope it helps.

    Genymotion issue with Windows 10 10586

    I use Genymotion for my Xamarin Android development, I know that both Xamarin and Microsoft provide their own emulator but, for my machine configuration Genymotion is the one I like most at the moment.

    This post is to help you find a solution in case the virtual device doesn’t boot on a machine after the upgrade to TH2 aka build 10586, with this message:


    obviously the message is meaningless, digging into device log file located at %LocalAppData%\Genymobile\Genymotion\deployed\  I’ve discovered that error depends on a network issue:

    0:00:01.362237 VMSetError: Failed to open/create the internal network ‘HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter #4′

    After doing several test and internet search I finally found the reason of the problem: no idea why but an option in the adapter settings was not selected:


    The option is: VirtualBox NDIS6 Bridged Networking adapter, if not selected, select it and try again, your emulator should now work (or at least, it worked for me)



    Hope it works for you too, otherwise good luck finding the solution, if you find it please share, Genymotion support for free licenses is far than optimal.

    Visual Studio 2013: Fixing NuGet package install error in Xamarin Android projects

    Recently, quite often indeed, I’m facing an issue trying to add some NuGet packages to a Xamarin Android project, in this particular case I was trying to add Xamarin.Android.Support.RecyclerView package.


    The error I get after clicking Install is:


    Some search on the internet provided me some solutions, the one working for me is changing Android version option from:


    to an explicit value (API 21 in my case)


    after this change, all packages get installed properly.

    Declarative event handlers in Xamarin Android

    In Android applications the UI components are totally isolated from associated activity so to ‘glue’ them you need to follow a ‘javascript like’ approach: find the element fist  and then interact with it. Let’s say you have a .axml file containing a button with id MyButton

            android:text="@string/Hello" />

    in the associated activity, to subscribe its Click event you have to write this code:

    public class MainActivity : Activity
      int count = 1;
      protected override void OnCreate(Bundle bundle)
       Button button = FindViewById<Button>(Resource.Id.MyButton);
       button.Click += button_Click;
      void button_Click(object sender, EventArgs e)
       (sender as Button).Text = string.Format("{0} clicks!", count++);

    If you, like me, come from XAML and love the declarative approach I’ve got a good new for you, there’s an alternative, just follow this steps:

    1-Add a reference to Mono.Android.Export library

    2-Declare you handler in .axml file this way:


    3-Refactor the code in associated activity this way:

    public class MainActivity : Activity
      int count = 1;
      protected override void OnCreate(Bundle bundle)
      public void button_Click(View v)
       (v as Button).Text = string.Format("{0} clicks!", count++);

    And you’re done!

    As you see the trick is to export the function, using the Java.Interop.Export attribute that also allows you to use a export the method with a different name, leave it empty if you don’t need to differentiate.

    Lot simpler, and cleaner… IMHO Smile