Part 2 - Supporting pre-Honeycomb Android using Support Packages

PDF for offline use
Related Links:

Let us know how you feel about this


0/250

The Android Support Package consists of libraries that back port some of the new API’s—such as fragments—to older versions of Android. So by adding the Android Support Package, we can run our application on Android 2.3 devices, as shown by the following screens:

   

Adding the Support Package

To include the support packages into your Xamarin.Android application include the Android Support Library v4 component into your Xamarin.Android project, as illustrated in the following screenshot:

Once the component has been added, change the target framework to Android 2.2 or higher:

Also, ensure that the minimum Android version targets the same API level:

Change MainActivity to derive from FragmentActivity

Any Activity that uses fragments must inherit from Xamarin.Support.V4.App.FragmentActivity. This class is a necessary part of the Support Package because it allows fragments to be hosted by activities, regardless of the version of Android. MainActivity requires only one small change—it must now inherit from Android.Support.V4.App.FragmentActivity:

[Activity(Label = "Fragments Walkthrough", MainLauncher = true, Icon = "@drawable/launcher")]
public class MainActivity : Android.Support.V4.App.FragmentActivity
{
   protected override void OnCreate(Bundle bundle)
   {
       base.OnCreate(bundle);
       SetContentView(Resource.Layout.activity_main);
   }
}

Change DetailsActivity to derive from FragmentActivity

DetailsActivity must also be changed from an Activity to a FragmentActivity. As FragmentManager is not compatible with pre-Honeycomb versions of Android, the Android Support Package includes a wrapper class, SupportFragmentManager, that provides backward compatibility. Each FragmentActivity has a SupportFragmentManager property, and DetailsActivity is changed to use the SupportFragmentManager instead of the FragmentManager:

[Activity(Label = "Details Activity")]
public class DetailsActivity : Android.Support.V4.App.FragmentActivity
{
   protected override void OnCreate(Bundle bundle)
   {
       base.OnCreate(bundle);
       var index = Intent.Extras.GetInt("index", 0);
       var details = DetailsFragment.NewInstance(index);
       var fragmentTransaction = SupportFragmentManager.BeginTransaction(); // Notice the change from FragmentManager to SupportFragmentManager
       fragmentTransaction.Add(Android.Resource.Id.Content, details);
       fragmentTransaction.Commit();
   }
}

After we complete these changes, we now have an application that can run on Android 1.6 and higher, and that uses fragments to adjust our UI to the size of our target device.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.