Affiliate links on Android Authority may earn us a commission. Learn more.
An introduction to Xamarin for cross platform Android development
Xamarin is a cross platform tool for building Android and iOS apps using Visual Studio (VS). It can potentially save you vast amounts of time by allowing you to build an app with a single code base and seamlessly port it to multiple platforms without drastically increasing development time.
Read Next: Cross-platform mobile development — challenges, options, and why you should consider it
Visual Studio is an integrated development environment (IDE) from Microsoft that many coming from a PC development background will be familiar with. Xamarin is an extension for Visual Studio. It started as a commercial project but was later purchased by Microsoft and made available for free through VS.
Today, Xamarin is among the most popular cross-platform options and gets a lot of support as a result. It has a lot of useful features and lets you code with C#, which some may find has a slightly more lenient learning curve than Java (the official language of Android Studio). Because it’s natively compiled, there’s no real performance cost and you’ll be able to accomplish a native-looking material design aesthetic – then just switch out the layout files and a tiny bit of code to achieve a native look on iOS.
Because it’s natively compiled, there’s no real performance cost and you’ll be able to accomplish a native-looking material design aesthetic
So, what’s the catch? Using Xamarin means you’re not using the official option from Google, which may in turn mean you have to jump through a few more hoops if you want to take advantage of the most recent features Android Studio (AS) has to offer, or make use of any particular libraries. There are workarounds in every case (here is how to use libraries), but it’s just something to keep in mind.
There is also often a slight wait for Xamarin to catch up with the latest platform updates. There may be some compatibility issues with certain libraries too. However, this isn’t the ‘official’ language and IDE for Android and you may find that employers prefer you to stick with Java. Note that app sizes are generally slightly larger than they would otherwise be, too.
Apart from those minor gripes, this is a perfectly valid choice for your Android development. If you’re already familiar with building apps in Android Studio, then the transition will be fairly painless. If you’re new to Android development, then it may prove to be a relatively gentle introduction.
Setting up Xamarin for Android development
To get started, you’ll need to download Visual Studio Community Edition 2017. It’s free and the installation process is nice and simple. You can get it here.
Now click ‘New Project’ and hopefully you’ll have the option to select ‘Android’ on the left under Templates > Visual C#. Now choose ‘Blank App (Android)’. This will allow you to build a native Android app!
If that option isn’t available, then you’ll need to click ‘Open Visual Studio Installer’, where you’ll be able to find extensions, add-ons, and more. Under the ‘Workloads’ tab, scroll down and find ‘Mobile Development With .NET’. This will install Xamarin and any other components you might need such as the Android SDK, an Android emulator and more. You also have the option to add other elements such as Xamarin notebooks, the Android native development kit (NDK), the Java SE development kit, and more.
I recommend unchecking the boxes for NDK, F# language support, and workbooks as this is a huge download otherwise – a warning dialog will come up if you’re removing anything that is needed. It’s still a pretty big download (15 GB for me!), which is one downside of using Xamarin. If you thought Android Studio with the SDK was a big installation, look out!
Of course, if you have a copy of the Android SDK lying around on your computer from previous work with Android Studio, then you can choose your components individually using the relevant tabs. But if you’re diving into Xamarin for the first time, you’ll need all of this.
With that selected, hit ‘Modify’ and it will close any open instances of VS and get to work. Hope you have a fast internet connection!
When that’s done, you can hop back in, choose a name for your Android project, and get to work!
Finding your way around and Hello World
Once you’re in, you’ll be greeted with a blank screen. Find the MainActivity.cs file using the Solution Explorer, on the right by default (which is backwards if you’re used to Android Studio!). This explorer is just showing you all the files and folders that make up your project. It looks daunting but you won’t need to touch most of them, so don’t worry just yet! MainActivity.cs is the equivalent of ‘ActivityMain.java’ for those with Android Studio experience; it’s where you’ll handle the code of your app.
Looking at the boilerplate code (code that has already been populated) on this screen, we can see some familiar-looking lines. SetContentView tells us where the layout of the views will be defined. It’s in the Explorer under ‘Resources > layout > Main.axml’. For those of you familiar with Android Studio, this is the equivalent of activity_main.xml.
It basically tells us this file is going to define the layout of views and graphical elements for the first ‘activity’ (screen). You can arrange things like buttons, text elements, and images here, and then tell them how to behave in the C# code. Open up that file by double clicking.
Notice that this is AXML, not XML. It’s basically XML though and most things you’re used to doing in AS will work just fine here. If you run into any problems, a quick Google will reveal what needs to be different.
You can also find a toolbox on the left of the visual designer for adding things like TextViews and the like and change properties in the relevant Properties window in the bottom right. For now though, hit the ‘Source’ tab at the bottom of the screen and then add the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:minWidth="25px"
android:minHeight="25px">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView1" />
</LinearLayout>
The LinearLayout should already be there and it defines how the elements will be arranged on the screen. We’ve just added a TextView, a box with some text on it.
That’s our first ‘Hello World!’ built in Xamarin. Sweet!
C# for Android
Let’s try a little C#. The differences are relatively minor and it’s easy, too.
using Android.App;
using Android.Widget;
using Android.OS;
namespace App1 {
[Activity(Label = "App1", MainLauncher = true)]
public class MainActivity: Activity {
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
TextView textView = FindViewById & lt;
Textview & gt;
(Resource.Id.textView1);
int count = 0;
textView.Click += delegate {
count++;
textView.Text = string.Format("Clicks: " + count);
};
}
}
}
What we’ve done here is to add an onClick. When we created our TextView in the AXML, we added an ‘ID’ and called it ‘textView1’. Since our layout is defined by that AXML, we can locate the view using that identifier and then handle clicks. We find the TextView with FindViewByID, just like in Java. The difference is how we handle our onClick. This uses a ‘delegate’, an object that contains information about a method (onClick in this case).
With that, press play to launch your emulator and install the app. Clicking on the text should cause it to show the number of times you’ve clicked. Feel free to go crazy with that…
We could also add a little extra logic to make this into a clicking game…
textView.Click += delegate {
count++;
textView.Text = string.Format("Clicks: " + count);
if (count == 5) {
textView.Text = string.Format("You won!");
}
};
It’s almost exactly the same as it would be in Java to do this.
There’s actually a really nice debugger here that goes to the trouble of highlighting the exact line where things go wrong. The emulator also runs as nicely and quickly, even on my Surface Pro 3. It sure was nice having that all set up for me along with the installation. This is actually a pretty nice experience, on the whole.
Closing comments
Many of the differences between C# and Java are largely semantic. For instance, if you want to use an inherited method, you do so like this:
protected override void OnPause() {
base.OnPause();
}
Notice as well that we used a colon to extend the class “public class MainActivity : Activity.”
You will find that occasionally you need to wrap your head around a new concept such as delegate, lambda expressions, or implicitly typed variables (using var). If you like the looks of Xamarin and want to learn more, the official resource explains everything clearly. If you’re coming from Java, then read Xamarin for Java Developers to gain a quick overview of the key differences.
I hope you found this little introduction to Xamarin helpful. Let me know what you think in the comments down below!
Do you use Xamarin? Is it something you might consider in future? Or will you stick with good old Android Studio? Who needs Apple money anyway, right?