Xamarin.Android - James Montemagno https://staging.montemagno.com/tag/xamarin-android/ https://staging.montemagno.com/content/images/2017/08/MonogramIcon_Orange_NoBuffer.png Xamarin.Android - James Montemagno https://staging.montemagno.com/tag/xamarin-android/ Hugo -- gohugo.io Tue, 13 Oct 2026 20:48:55 GMT 60 New & Improved Xamarin.Android Templates for Visual Studio https://staging.montemagno.com/new-improved-xamarinandroid-templates-for/ 598df8f2c121b60019bf3005 Fri, 10 Jul 2015 00:38:21 GMT

It has been a bit over a year since I first introduced my Xamarin.Android Templates pack for Visual Studio and things sure have changed in the world of Android since then. Early on the templates pack only introduced a few item templates for menu items and a simple implementation of the Navigation Drawer, my favorite way to navigate in Android. Then this March Google went and changed everything with AppCompat and the introduction of the new Toolbar. I rushed to update all of my templates to include all these nice new features. It looks like it is that time of the year again with the new Android Design Support Library, which yet again changes how we implement the Navigation Drawer and of course let’s not forget about the big change to AppCompatActivity. 

I am pleased to announce the latest release of my templates that incorporate all of these changes to make it easy to get up and running with AppCompat and the new fancy navigation drawer featuring the NavigationView.

You can grab these templates from the Visual Studio Gallery by going to “Tools->Extensions and Updates” in any flavor of Visual Studio and searching for Xamarin.Android Templates. 

Once installed you will see a few new Project Templates under Android to create a blank app that features AppCompat or a full Navigation Drawer enabled app also featuring AppCompat:

Once you have your app up and running you might want to add a few new menu items such as search, share, or just a menu item and I have you covered:

Of course everything is open source on GitHub so you take take a peek at what I am doing in the templates. Additionally, if you already have an app and are looking to upgrade your navigation drawer or tabs to the new material support library implementations then look no further than my Xam.NavDrawer GitHub repo that has been updated with an awesome new example! 

I hope you enjoy these new updated templates and I look forward to your feedback or suggestions for future updates!

]]>
Announcing Bike Now on Android, for Seattle's @CyclePronto Bike Share Program https://staging.montemagno.com/announcing-bike-now-on-android-for-seattles/ 598df8f2c121b60019bf3025 Mon, 13 Oct 2014 14:15:16 GMT Ever since I first saw Hubway in Boston I was excited for the hopes that one day Seattle would get it’s very own bike share program. Well, 2014 is the year this happens with Pronto Cycle Share is making it a reality.

I was a bit worried that there would be no official app to help track bikes around the Sound, so I decided to take up the challenge. I had a great start with Jérémie Laval’s wonderful Moyeu and morphing it for the Pronto Cycle.

Since Jérémie’s project was open source and built completely with Xamarin, it was easy for me to get off the ground running and leverage several libraries that I am familiar with.

Today, I am pleased to introduce Bike Now for Android and the Pronto Cycle Bike Share program that is launching today in Seattle.

This beautifully crafted app enables you to:

  • Track all Pronto stations on a visual map

  • See past 30 minute history of bike data

  • Favorite stations for quick access

  • Easily see stations nearby

  • Tap to navigate to a station near you

I have many more features planned for the app including Android Wear support, account history, and eventually an iOS and Windows Phone version as well. You can download the app right now on Google Play and learn more at www.bikenowapp.com.

]]>
Enhanced Xamarin.Android Designer with Tools Attributes https://staging.montemagno.com/enhanced-xamarinandroid-designer-with-tools/ 598df8f2c121b60019bf3027 Sun, 24 Aug 2014 21:29:26 GMT The announcement of Android L Developer Preview support for Xamarin.Android developers brings tons of goodies to start playing around with, but did you know that there has been several updates to the Android designer as well? If you look through the release notes of Xamarin Studio 5.3 you will several enhancements such as the new Android L & Wear themes and devices, but also support for Action Bar menu icons and navigation style via the menu and actionBarNavMode XML attributes. More information on those attributes can be found at http://tools.android.com/tech-docs/tools-attributes#TOC-tools:menu. So, let’s take a look at these new features in the Alpha Channel.

Tools XMLNS

To take advantage of any of the features you will need to add this attribute to your root node in your layout:

 xmlns:tools="http://schemas.android.com/tools"

So your layout might look something like this:

Now we can take advantage of the tools and other attributes and add them onto our root node.

Normally your menu’s live completely separate away from your layouts, however the tools attributes allow you to get a preview right in the designer. First we will want to add the tools attribute:

tools:menu="menu_name"

Notice that we don’t use any @menu or anything like this. It is just referencing the name in the Resource/Menu folder. This will give us a nice preview:

Additionally, you might be using tabs or a spinner as part of your navigation in your ActionBar and you can now visualize this with another attribute:

tools:actionBarNavMode="tabs"

The actionBarNavMode can be set to tabs, list, or standard. I actually use a list navigation in My StepCounter, so this is great to be able to visualize:

That is just the beginning as Jérémie Laval has hinted at some more awesome updates coming soon:

Issues with Menu?

If you are having issues with the tools:menu property you might need to remove the Unicode BOM from your xml file. This is just a side effect currently of how the xml files are generated. Once you delete the 3 invisible bytes you will be able to browse things just fine. It is relatively easy and quick to do this. First make sure the file is CLOSED inside of Xamarin Studio. Then you will want to say open in HEX Editor:

Now simply delete the first 3 bytes on the right hand side that:

Alright you are all set now :)

]]>
My Favorite Xamarin Studio Features https://staging.montemagno.com/my-favorite-xamarin-studio-features/ 598df8f2c121b60019bf3029 Thu, 07 Aug 2014 23:05:12 GMT There have been a lot of exciting announcements recently from Xamarin for developers. First, is that Xamarin Indie now has a monthly subscription option for just $25 a month! Then there was the release of Xamarin Studio 5.2, which brought awesome new features such as side-by-side editing and awesome new NuGet updates. I have been a Visual Studio user for probably over 10 years and I have been using Xamarin Studio for nearly 3 years now. I have to say I find myself more and more developing on my Mac inside of Xamarin Studio. It is finely tuned for mobile development and has some amazing features packed into it, so I thought I would point out my top 3!

Source Analysis

I have been spoiled for years with ReSharper on Visual Studio, however Xamarin Studio actually ships with Source Code Analysis right out of the box. With the launch of Xamarin 3 this feature has been enabled by default, but I have been using it for some time and it makes daily development so much better. Simply look on the side of your code file for an overview of all the enhancements and optimizations you can make to your code.

TestFlight Integration

Distributing beta builds of my apps to my testers is always tricky. On Google Play you can have a beta/alpha channel and upload your APK and on Windows there is a beta option, but you have to leave the IDE. With TestFlight integration into Xamarin Studio you can easily upload your iOS applications with 1 click!

Workspaces

I am often working on multiple apps at the same time and Workspaces make it extremely easy to work on everything all at once. With this feature you don’t need multiple instances of Xamarin Studio open to work on multiple libraries or apps. Simply create a workspace and add as many solutions or projects as you would like.

So Much More

These are just 3 features I chose to highlight, but there is so much more include all of the unit test features, app archiving, universal search, version control, and about a thousand other awesome features. I would love to see what features of Xamarin Studio you love the most.

]]>
Extending Xamarin.Forms Monkeys App with XAML and Images https://staging.montemagno.com/extending-xamarinforms-monkeys-app-with-xaml-and/ 598df8f2c121b60019bf302e Fri, 13 Jun 2014 19:56:42 GMT Last week I posted an introduction to Xamarin.Forms article on the Xamarin blog. I went over a simple master/detail flow with a list of monkeys that data bound to a ListView, and then navigate to a detail view displaying more information about the monkey when selected. It was a pretty simple implementation and I wanted to dive deeper into adding functionality.

XAML Please!

While the blog post got a great response, I got a lot of questions about why I did the sample in code behind and not XAML. Well, I love me some XAML, but I really like how the code behind reads. Reading the code reminds me of reading XAML, so I have mostly stick to doing everything in the code behind, but fear not I decided to publish the full sample in XAML as well! So the core of it is really simple, instead of creating a new class to add a page inside of your preferred IDE, you will see an option to add a Xamarin.Forms XAML page:

This will give you the XAML and the binding to the code behind as well. Intellisense with Xamarin.Forms XAML is only available in Xamarin Studio currently, but it is pretty easy to follow if you have done XAML development before. For the main list I am going to put a ListView inside of a ContentPage root element and then fill in the ItemTemplate directly in the ListView. I can add direct bindings with the same syntax used in normal XAML. Here is what the master and details page look like:

The key here is in the root which is where we specify the:

xmlns="http://xamarin.com/schemas/2014/forms"

and the main page that it binds to:

x:Class="Monkeys.Views.MonkeysPage"

You can read more about XAML in the Xamarin.Forms docs, but let’s get to some fun and add some new functionality!

Monkey Images!!

Xamarin.Forms makes it extremely simple to work with images either embedded or that need to be downloaded from the internet. The Image control itself has a Source property that you can just bind a string of images URL to. So first let’s update our Monkey data model to have a new string called Image and I will find a bunch of images on wikipedia to use for the monkeys:

Now we just need to update our ListView’s ItemTemplate from TextCell to a ImageCell, which as you guessed it has an image on the left hand side that you can bind to. This means I simply need to bind the ImageCell.ImageSourceProperty to my new Image property.

Now our monkeys are in our list!

We can also add the image to our details page by creating a new Image and setting the Source to the Monkey’s Image property. I will then add it into a StackLayout under the details before adding it into a ScrollView incase the text or image is really large.

Notice that I set a few important properties. First is the Image’s Aspect property to Aspect.AspectFit to ensure it doesn’t get cropped at all and fills as much as possible. I also set the VerticalOptions = LayoutOptions.FillAndExpand of the StackLayout and Image to ensure they fill vertically as much as possible. This results in a beautiful view:

Customize Those Cells!

One thing that drives me crazy is resizing of images in cells. On iOS it is really a pain to try to fix this with the default built in cells even in Objective-C. In fact there are tons of threads on StackOverflow and the end result is that you will need to create a custom UITableViewCell and override the creation of the ImageView. I will have to dive into this in another blog post, but for now I know I can at least fix up Android since I have access all of the controls in the ImageCell. To do this, I am going to create my own cell called AspectImageCell that inherits from ImageCell and then I will implement a custom renderer on Android, and since I am not implementing anything special on iOS or Windows Phone it will simply drop back down to ImageCell. The final step is to now use our new AspectImageCell instead of the standard ImageCell for our ItemTemplate.

Beautiful!

And there you have it. I have update the source code from both code behind and XAML! You can grab the code from my GitHub page: https://github.com/jamesmontemagno/Xamarin.Forms-Monkeys

]]>
My StepCounter for Android goes Live & Open Source! https://staging.montemagno.com/my-stepcounter-for-android-goes-live-open/ 598df8f2c121b60019bf3031 Wed, 23 Apr 2014 14:38:00 GMT The past two weeks have been an absolute joy to take Michael James’ My StepCounter app for iOS and bring it to Android with C# and Xamarin. I have been quietly working out of my own personal fork trying out the latest Android KitKat sensor and user interface APIs. I ran a very successful beta test with nearly 40 people with great feedback and I am extremely proud to announce that My StepCounter is available today on Google Play! And heck, we even launched a website for the apps: http://mystepcounterapp.com/

Starter Compatible

Xamarin Starter Edition CompatibleXamarin Starter Edition holds a special place in my heart as it allows anyone to try out Xamarin for FREE to build full apps and publish them to the app store! There are some limitations, but I am extremely proud to say that My StepCounter is 100% Starter Compatible just like the iOS version! By leveraging an ADO.NET database and a few other optimizations I have plenty of room to continue to grow the application.

Open Source

I basically put everything on GitHub that I work on and My StepCounter is no different. Michael James’ has officially excepted my pull request to merge Android into his main repo. We have added full documentation, license, support forums, and a whole bunch more awesome. Head over to the main repo at: https://github.com/MichaelJames6/My-StepCounter

Learning Experience

I have been documenting my experience this entire time as I have been developing and I have a few more things to cover still as I explore all the new APIs with C#. Here is a recap of what I have blogged about so far:

Here is what is still to come:

  • Animations in Android
  • Leveraging an ADO.NET database
  • Project Retrospective

A Special Thanks

I have to thank a few people who helped me out with this project:

  • Jérémie Laval - for some android help and testing. Also he launched an awesome new Android app today called Bikr, you should check it out if you cycle!
  • Michael James - for starting My StepCounter!
  • All my beta testers!
  • Android Design Community - for the awesome UI ideas
  • My Translators: Jérémie, PatrikSelin, rasumseeg, jramirezdev, claudiut, d1m0nh, & fsdachs for helping me launch the app with Finnish, German, French, Romanian, and Spanish support! More to come soon, feel free to contribute
Get it on Google Play

I hope you give My StepCounter a try and I would love your feedback! My StepCounter uses the built in step sensor on select devices running Android 4.4+. This means as of today I support 85 devices (20+ are unique)! Here is the full list of supported devices: Nexus 5, G2 Mini, G Pro 2, Vu3, L90, G Flax, G2, K91, Moto X, Secret Up, Secret IP, Galaxy S5, Galaxy S4, Noe 3, Tab Pro 8.4, Galaxy Round, Z2 Table, Z1, Z2, Z2 Ultra, Z1 Compact.

This is a joint release with Jérémie Laval’s Bikr Android app, check it out too!

]]>
Part 3: My StepCounter Android: Pretty UI! https://staging.montemagno.com/part-3-my-stepcounter-android-pretty-ui/ 598df8f2c121b60019bf3034 Fri, 18 Apr 2014 17:50:34 GMT I am no UI expert that is for sure, but I really like what Michael James did with the iOS version of My StepCounter. He made a nice background that changed colors from Red to Green, had a chromeless UI, and utilized very nice fonts. I want to take advantage of some of the work he did and also customize it for android.

Transparent ActionBar

I Wanted to ensure that the full screen was being utilized for this app, but still wanted to take advantage of the unique actions that I can put in the ActionBar. Luckily Android is highly customizable with styles and themes. To create a transparent actionbar you need to override your themes.ActionBar style and give the android:background and android:backgroundStacked a transparent colors. Additionally I wanted to only show the title and then style the TextStyle to be a bit larger and also use a sans-serif-light.

This bit of code results in a stunning and beautiful look:

Pretty Fonts

I was really impressed with the font selection and usage on the iOS version and I wanted to bring that over to Android. Since I am targeting Android 4.4 I can use all of the nice Roboto fonts built in. If I was targeting an older version I could have used my Roboto.TextView control, however all I need to do is set the android:fontFamily to:

  • san-serif
  • sans-serif-light
  • sans-serif-condensed
  • sans-serif-thin

These are all great fonts and when combined with a nice background I get a nice visual look:

Fancy Background

In the iOS version Michael created a custom ProgressView that would change the background RGB based on the percentage that you passed into it. I was actually able to re-use nearly all of this code and put it into a shared file. The main difference was just what property I was settings and how I was creating a new color:

As we can see I have to do a lot of #if defs, but it is nice to re-use all of this RGB arrays so we get the same color on the device. The screenshot I showed earlier you saw a blue background, but what I didn’t show you was how I created this. What I actually did was make my root view the ProgressView, which is a FrameLayout, and then I overlaid another FrameLayout with a blue background on it.

This blue frame layout will be animated later, but here are a few screen shots of what the progress view looks like as I move it:

No Boundaries

After having a few people test out the app I got some instant feedback, which was that I should extend the views up to the System Bar and Navigation Bar. This is a brand new feature in Android 4.4 so why not take advantage of it! It was actually really simple. The first thing I needed to do was add android:windowTranslucentNavigation=“true” and android:windowTranslucentNavigation=“true” to my style:

Now to ensure that any content on the bottom of the screen didn’t overlap there is an important property to set, which is: android:fitsSystemWindows=“true”. I had to wrap my two text views in a FrameLayout which is where I set this property:

And here you have it the final UI:

So there is my base UI with the same ProgressView that we are using on iOS now on Android with pretty fonts as well. Next up is Animations!

]]>
Part 1: My StepCounter Android: Step Sensors https://staging.montemagno.com/part-1-my-stepcounter-android-step-sensors/ 598df8f2c121b60019bf3036 Sat, 12 Apr 2014 21:24:00 GMT In February, my fellow Xamarin Michael James published a wonderful app for iOS called My StepCounter. This app uses the new CoreMotion apis in iOS 7 to track your steps on your iPhone 5s. This isn’t a new concept and there are plenty of devices and apps out there that do step tracking, but what makes My StepCounter special is that Michael gave it a beautiful simplistic UI & beautiful animations. On top of that he created it all to be 100% compatible with Xamarin Starter Edition! This is extremely impressive and demos the power of Starter Edition for anyone to start creating apps in C#.

Introduced with Android 4.4 was a new step sensor hardware support, which happens to be supported on my Moto X. So naturally as an Android development lover I wanted to test out these new APIs and create My StepCounter for Android. My goal is pretty simple:

  • Track Daily Steps with new APIs
  • Keep the same look, feel, and animations
  • Maintain Starter Compatibility
  • Maximize code re-use from iOS version
  • Add support for browsing history

So with this in my mind and a Southwest plane ride back from Arizona without internet I started my journey on bring My StepCounter to Android.

Step Counter & Step Detector

Android 4.4 introduced 2 new sensors apis for step tracking: TYPE_STEP_DETECTOR This sensor triggers an event each time the user takes a step. Upon each user step, this sensor delivers an event with a value of 1.0 and a timestamp indicating when the step occurred.

TYPE_STEP_COUNTER

This sensor also triggers an event upon each detected step, but instead delivers the total accumulated number of steps since this sensor was first registered by an app.

These 2 types seem extremely similar, but the documentation says something very important:

"Be aware that these two step sensors don’t always deliver the same results. The TYPE_STEP_COUNTER events occur with a higher latency than those from TYPE_STEP_DETECTOR, but that’s because the TYPE_STEP_COUNTER algorithm does more processing to eliminate false positives. So the TYPE_STEP_COUNTER may be slower to deliver events, but its results should be more accurate."

So I wanted to test them out for accuracy. For testing I put my main logic in an Activity, although I know I would probably want to put this in a background service at some point. To be able to get notification sensors I had to implement ISensorEventListener, which has 2 methods in it: OnAccuracyChanged: called when the accuracy changes. OnSensorChanged: called when the sensor gets an update.

Before I could start testing out these sensors I wanted to make sure that my app could use them and have a way of detecting if the device my app was running on was compatible. So I had to add a little xml to the AndroidManifest.xml and also created a little helper method:

Now to take advantage of these sensors. I didn’t have to do anything for the accuracy changed since I was not interested in that, but for Sensor changed I had to either increase my step count for the step detector or calculate the total for the step counter so I could test accuracy:

With this code in place the only thing left to do was to register for the sensors. This involves grabbing the SensorManager and attempting to get the default sensor for the specific type and then registering the listener. It has multiple delay types, but normal seems to be the way to go:

Now that my sensors are all setup the last thing to do is put in a little UI to do some testing:

There you have it my very first step counter!…. Alright well it isn’t nearly done at all, but this was just Part 1! Here is what I have mapped out currently on my timeline:

  • Part 2: Step Counting in a Bound Service
  • Part 3: Pretty UI
  • Part 4: Pretty Animations
  • Part 5: Saving Info to ADO.NET Database
  • Part 6: Shipping this app!
]]>
Xamarin.Android SwipeRefreshLayout for #MvvmCross https://staging.montemagno.com/xamarinandroid-swiperefreshlayout-for-mvvmcross/ 598df8f2c121b60019bf3037 Tue, 08 Apr 2014 16:30:00 GMT I was very excited to see that the latest version of Support v4 for Android was updated to include as most people would says it a “Pull to Refresh”… or as Google would call it a “SwipeRefreshLayout”. It is now available in the Xamarin.Android Support v4 Component so we should probably take advantage of it! This is actually a really slick Layout that you can make the parent of any 1 layout and when the user swipes down on it you will get notified that you are supposed to refresh the content. This means you can now get rid of all of your refresh icon buttons in your UI and follow the same patterns Google has for their apps that your users will be used to.

Naturally I wanted to implement an MvvmCross version of this since I did an MvvmCross binding for UIRefreshControl on iOS a while back. So the goals here are simple:

  1. Execute an ICommand when someone pulls down to refresh

  2. Bind a bool to begin and end the refreshing spinner

So I created a very very simple MvxSwipeRefreshLayout which you can find the Gist for RIGHT HERE! In addition you will just need to implement a bit of code in your .axml layout and in your code behind to set the Refresh command.

]]>
Xamarin.Android Templates Pack! https://staging.montemagno.com/xamarinandroid-templates-pack/ 598df8f2c121b60019bf3038 Sun, 30 Mar 2014 03:31:59 GMT Xamarin.Android already ships with a bunch of great project templates for Visual Studio, however I find that there are a few things missing. I usually start a new project with a Navigation Drawer and I am always adding new Menus, but I can never seem to remember every little bit of XML that is needed for some complex menus such as share and search. This is why I have created the Xamarin.Android Templates Pack. This is the first release that includes these items that I have listed. You can download it immediately from the Visual Studio Gallery and browse the code on GitHub.

Included in the Menu Items are not only the XML required but also the code behind that will help you implement it. Once you have the Template pack installed you will see the items when you starter a new project or add an item to the menu folder in Resources.

Navigation Drawer:

Menu Item:

Share Menu:

Search Menu:

I am going to be continuing to add more and more templates and please feel free to add an issue or do a pull request if you want to see something.

]]>
Google Plus Services, Login and +1 in Xamarin.Android https://staging.montemagno.com/google-plus-services-login-and-1-in/ 598df8f2c121b60019bf3044 Fri, 15 Nov 2013 19:31:00 GMT I have been dabbling around recently with integrating Google Play Services into Android applications. Play Services are pretty interesting as they offer up a nice set of functionality including a G+ Sign In button and +1 sharing on G+. This is pretty intriguing to me because I have been building out a podcast streaming app for the Dot Net Rocks show. I wanted to build out a small sample to test what the details page might look like allowing my users to +1 and share a link. I also wanted to see what information I could get on the user when they logged in and create a small profile page. So here is how to get started:

Add the Component:

UPDATE V13 is now available in the component store, so no need to download the old version. Get the new component here.

Currently on the Xamarin component store there is a binding for Play Services v12 (and a blog post about it) that you can add to your Xamarin.Android project. This is great as they have done all of the hard work for you, but technically Play Services are on v13, so you will actually have to download the older Play Service v12 manually as instructed here (the android sdk should be installed in: /Users//Library/Developer/Xamarin/android sdk). After this has been added there is one important thing to do which is to increase your Heap size of your app as the Play Service binding is large. You can do this under your project properties -> Android Build -> Advanced -> Java Heap Size. Then everything will build!

Settings up Google App & API:

The next part is bit in depth as you will need to setup a google app and the API that the google play services will talk to. Google has a pretty great guide, but here are the pointers: *Note I am doing this on Mac OSX 10.9, on Windows the locations will differ.

  • Create new app at Google App Console

  • Go to Services and enable Google+ API For this next part I switched back to the old console

  • Get the SHA1 for your keystore (I am using debug to test, but you will want to use a final release keystore that you have to create before you ship).

  • Find your debug.keystore in: /Users//.local/share/Xamarin/Mono for Android/debug.keystore

  • Copy it into Java in /Library/Java/Home/bin

  • Run this command in terminal after navigating to that directory:

keytool -exportcert -alias androiddebugkey -keystore <path-to-debug-or-production-keystore> -list -v
  • This will output your SHA1 you will need:
  • Use this to add oAuth to your app! Alright let’s integrate this puppy into our app! First thing I want to layout is a sign in button, +1 button, log out button, and then a small details section. Here is what my axml is looking like at this point:

Sign In and Out: Next we need to add some backend code. You will need to add the following permissions for Google Plus Login to work: Internet, Get Accounts, and Use Credentials. The first thing to do is to create our GooglePlusClient and grab our LoginButton and PlusOneButton:

In AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
plusClient = new PlusClient.Builder(this, this, this).Build();
googleLoginButton = FindViewById<SignInButton>(Resource.Id.sign_in_button);
plusOneButton = FindViewById<PlusOneButton>(Resource.Id.plus_one_button);

Let’s first implement our login button. I have created a helper method to handle the connection that I am calling ResolveLogin and when I get a connection it triggers an OnActivityResult:

private void ResolveLogin(ConnectionResult result)
{
  if (result.HasResolution)
  {
    try
    {
       result.StartResolutionForResult (this, 9000);
    }
    catch (Android.Content.IntentSender.SendIntentException e)
    {
        plusClient.Connect ();
    }
  }
  else if(progressDialog != null &amp;&amp; progressDialog.IsShowing)
  {
    progressDialog.Dismiss ();
  }
}

protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
  base.OnActivityResult (requestCode, resultCode, data);

  if (requestCode != 9000)
    return;

  if (resultCode == Result.Ok)
    plusClient.Connect ();
  else
    progressDialog.Dismiss ();
  }
}

Then we will need to implement 2 different interfaces IGooglePlayServicesClientConnectionCallbacks, IGooglePlayServicesClientOnConnectionFailedListener. In addition I will also try to connect on start of the activity and stop on end of activity.

public void OnConnected (Bundle p0)
{
  progressDialog.Dismiss ();
  RefreshPlusOneButton ();
  UpdateProfile ();
  Toast.MakeText (this, "Connected!", ToastLength.Long).Show ();
}

public void OnDisconnected ()
{
  Toast.MakeText (this, "Disconnected!", ToastLength.Long).Show ();
}

public void OnConnectionFailed (ConnectionResult result)
{
  if (progressDialog.IsShowing)
    ResolveLogin (result);

  connectionResult = result;
  Toast.MakeText (this, "Connection Failed!", ToastLength.Long).Show ();
}

In our OnCreate we will also now want to register for these callbacks:

plusClient.RegisterConnectionCallbacks (this);
plusClient.IsConnectionFailedListenerRegistered (this);

To handle the click event of the Sign in button, we simply have to check to see if we are logged in and if not try to sign. Google handle the rest:

googleLoginButton.Click += (sender, e) =>
{
  if(plusClient.IsConnected || plusClient.IsConnecting)
    return;

  progressDialog.Show();

  if (connectionResult == null)
    plusClient.Connect();
  else
    ResolveLogin(connectionResult);
};

Once we are connected we can pull in the connected user’s data:

private void UpdateProfile()
{
  profileTextView.Text = plusClient.CurrentPerson.DisplayName;
  nickNameTextView.Text = plusClient.CurrentPerson.Nickname;
  aboutTextView.Text = plusClient.CurrentPerson.AboutMe;
  imageLoader.DisplayImage (plusClient.CurrentPerson.Image.Url, imageView, Resource.Drawable.default_icon);
}

If the user wants to log out we just have to revoke permission on the PlusClient and implement the IOnAccessRevokedListener interface:

logoutButton.Click += (sender, e) =>
{
  if(!plusClient.IsConnected || plusClient.IsConnecting)
    return;
  plusClient.RevokeAccessAndDisconnect(this);
};

+1 Button: Adding the +1 is extremely simple after you have finished implementing the login button. When you call Initialize on the button you can pass it the URL and the PlusClient and it will handle the rest. I simply put this in a helper method so I can call it when the activity Resumes, Connects, Disconnects, or access is revoked:

private void RefreshPlusOneButton ()
{
   plusOneButton.Initialize ("http://blog.xamarin.com/microsoft-and-xamarin-partner-globally/", 0);
}

There you have it, implementing Google Plus Sign In and a +1 button! I have the full source code on GitHub!

]]>
Beautiful Android Compat Roboto Fonts in Xamarin.Android https://staging.montemagno.com/beautiful-android-compat-roboto-fonts-in/ 598df8f2c121b60019bf3048 Fri, 20 Sep 2013 18:59:07 GMT In android 4.1 and 4.2 Google did something amazing, which was add the roboto fonts as a default font family that you can switch between. It is as easy as setting “sans-serif”, “sans-serif-light”, “sans-serif-condensed”, and “sans-serif-thin” as the android:FontFamily.

However the obvious issue here is that this is only available in 4.1+ (with thin only being available in 4.2). So if you want to target older platforms you have to do some custom themes, or different layouts and that is no fun for anyone. These fonts are beautiful and everyone should be able to use them. It is also completely possible since you are able to load custom fonts. In Xamarin.Android it is extremely simple. All you have to do is add your fonts to you asset folder and then:

Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-LightItalic.ttf");

However this is going to be no fun if you have to set it in the code behind for each and every text view. We want to set it in the axml! To do this we are going to have a custom TextView (we will call it RobotoTextView) and it will have a custom attribute (we will call it typeface).

The RobotoTextView will check the custom attribute for the typeface attribute (such as roboto_thin or roboto_light) and then load up the correct font to display. It will also do some caching as well so we don’t load them up tons of times.

After that it is as simple as putting some stuff in you axml. First is to add an xmlns definition. I like to use res-auto and let it figure it out:

xmlns:local="http://schemas.android.com/apk/res-auto"

Then just a com.refractored.controls.RobotoTextView instead of TextView and set this property:

local:typeface="roboto_thin_italic"

Now you are all set! I have setup a full github repo with source code and example!

Your result will look like this:

]]>
Effective Navigation in Xamarin.Android: Part 1 - Navigation Drawer https://staging.montemagno.com/effective-navigation-in-xamarinandroid-part-1/ 598df8f2c121b60019bf3049 Fri, 06 Sep 2013 04:56:00 GMT When designing your app you have probably wondered about what type of navigation is the best to use. Dashboards, navigation lists, spinner drop downs, tabs, and fly out menus are all still prevalent and valid choices, however, Google has recently made a huge push to use their new standard Navigation Drawer control.

So what is a Navigation Drawer?

Similar to a flyout menu made famous by Facebook, the Navigation Drawer is designed to be swiped out from the left side of you application. The main difference is the navigation drawer slides on top of your main content and dims it out. This is unlike flyout which actually pushes your content off screen and is more jarring for your user.

As you can see here, the user will slide or press the home button to slide out the navigation drawer, and then select which section they would like to go to next.

Why Navigation Drawer?

1.) Now a standard control in the Support v4 library and ties directly into the Action Bar.

2.) Easy to implement with a Fragment first approach.

3.) Highly customizable. Use for navigation, account selection, or a combination of both. The possibilities are endless really.

4.) User familiarity as Google and others have already upgraded nearly all of their applications to follow this navigation scheme.

Let’s Code!

So enough background on the Navigation Drawer. Let’s write some code in Xamarin.Android!

When designing for the Navigation Drawer, you should first think of your apps flow. The navigation drawer is part of your main activity and is a container for all other sections, which are fragments that are swapped in and out. In this example I have the following:

  • Home Activity: Consists of Navigation Drawer Layout
  • Browse Fragment: Grid of images to browse through
  • Friends Fragment: Contains a ViewPager with friends list
  • Profile Fragment: Contains a small profile and image of the user

Create your Drawer Layout: This is the standard layout that Google recommends, which is a “DrawerLayout” as the root object with a “FrameLayout” to contain your main content or fragments that you will swap in and out. After that, you then have a “ListView” which is your actual Navigation Drawer. In this example we will just use a standard list, but you could completely customize it with headers, footers, or change it to something completely different.

Initialize the Drawer List

In this sample, I am simply creating an array of sections that my application might have, however you can customize your ListView to have a custom adapter that will display images or other information.

The last thing I am doing here is registering for an ItemClick event on my ListView to detect when the user selects a section.

Handle Navigation Click Events

Since we have registered for an ItemClick event “DrawerListOnItemClick” we will implement this method to replace the Resource.Id.content_frame with the fragment that the user has selected based on the position.

In this example I am using the SupportFragmentManager because I am going to be using a ViewPagerIndicator which takes Support v4 Fragments. However, if you are not using this you are free to use the standard FragmentManager. After I replace and commit the fragment, the last things to do are to set the correct checked position in the ListView, update the ActionBar with the title of the current fragments, and most importantly, close the drawer.

Listen for Drawer Events with ActionBarDrawerToggle

Each DrawLayout has a DrawerListener which is an ActionBarDrawerToggle that is used to notify us when the Drawer is opened, closed, state changed, or had slid open. In the sample you will find a class called “MyActionBarDrawerToggle.cs,” which implements all of the proper methods.

You will want to create a new “MyActionBarDrawerToggle” in your OnCreate, which takes in the current Activity, the icon to use, and a few strings to display if the user long presses on the toggle. After you have created the new Toggle you will want to implement the DrawerOpen and DrawerClosed events to update the ActionBar title and to also update the OptionsMenu. Finally you need to set the DrawerListener for your Drawer to actually listen for these events.

The standard drawer icons can be downloaded from Google.

Wrapping it up:

The other last few steps allow the user to open and close the navigation drawer by touching the app icon in the ActionBar. Simply set the SetDisplayHomeAsUpEnabled and SetHomeButtonEnabled in your OnCreate and then ensure that you synchronize your DrawerToggle throughout the main activities lifecycle.

Compatibility:

The navigation drawer ties directly into ActionBar, so if you are looking to target older platforms look into using ActionBarSherlock or the new ActionBarCompat(support v7) libraries. Full MvvmCross support is also available with a little adjustment by using a CustomPresenter to intercept navigation to present the fragments. A full example is available on GitHub.

Fragments inside of fragments!

Everything inside of the navigation drawer is a fragment, so that can lead to some interesting scenarios if you are using something like a ViewPagerIndicator, which also consists of fragments. Do not fear as you can use nested fragments! Simply provide the ChildFragmentManager instead of the standard FragmentManager and this will cover you!

Design Consideration:

Override OnPrepareOptionsMenu and remove any action items that are related to the content view. It is best practice to only show action items that pertain to the Navigation Drawer when it is open.

After the user first installs your application you might want to open the Navigation Drawer when they first load your application. This will allow your users to become familiar with the different sections of your application.

There you have it! A beautiful navigation model for your application. Check out full sample code available on GitHub.

Update! I presented on Navigation at Xamarin Evolve 2014:

]]>
Some more code! https://staging.montemagno.com/some-more-code/ 598df8f2c121b60019bf304d Sun, 11 Aug 2013 20:04:13 GMT So before motzcod.es existed I did a lot of blog posting about code and such over on motzwrit.es. As tumblr doesn’t allow a good way to transition posts I just wanted to create a nice archive here:

Windows Phone: Amazing - 1 Feature = Windows Phone Toolkit

Windows Store: Re-Use your WP Isolated Storage Settings in Windows Store Apps

Android/Xamarin.Andriod: The APK Dilema: To Split or Not to Split Making Theme.Holo Look awesome with gradients Mono for Android AdMob6 BInding Mono for Android: GridView in my ScrollView Mono for Android: Swipe/Fling Tabs in List VIew Mono for Android: Fix the DatePickerDialog Month Mono for Android: Load more items in list view when scroll to end Mono for Android: Remove that empty text view Mono for Android: Theme your app: part 2 ListView Fast Scroll with SectionIndex in Mono for Android How to use Theme.Holo in Mono for Android

Misc: A broken process (A look at mobile development releases) Get your LINQ ordeby right WPF Background opacity magic

]]>