Tag Archives: Xamarin Android

Advanced decorating of Xamarin Forms Slider for Android…

Alright so today I’m gonna take you guys through a journey of decorating a Xamarin Forms Slider control in Android…

Well we all know how basic the default Slider control in Xamarin Forms, but worry not, there are plenty of ways to decorate it with awesome features,specifically for Xamarin Android! 😀

It all started a few weeks back when I was playing around with the Slider control to add  a whole bunch of complex visual features in one of my company apps.

Let’s get started…

Alright, first thing first, we need set up our Custom Slider control first and attach it’s Custom renderer in Android.

So here goes the Custom Slider control subclassing in Xamarin Forms project…

namespace WhateverYourNamespace
{
    public class CustomSlider : Slider
    {

    }
}

 

Next set up the Custom Slider Renderer in your Android project…

[assembly:ExportRenderer(typeof(CustomSlider), typeof(CustomSliderRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class CustomSliderRenderer : SliderRenderer
    {
        protected override void
                 OnElementChanged(ElementChangedEventArgs<Slider> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
		// All the customization will go here
            }
        }
    }
}

 

How would I consume this in XAML you ask? Just as another ordinary view… 😉

<StackLayout>

	<local:CustomSlider 
	HeightRequest="7" 
	WidthRequest="350" 
	HorizontalOptions="Center"
	Minimum="0" Maximum="100" />

</StackLayout>

 

Now keep in mind all the customization that we are doing later will be done within this custom renderer.

Something to keep in mind is that,

the Xamarin Forms Slider control’s Android run time native counterpart is the SeekBar…

So the more you aware of the SeekBar’s properties, the more customization you could play around with! 😉

Alright let’s start decorating… 😀

Decoration 1 : Change color theme!

Want to change the color theme of your Slider? Here we go…

Let’s see the code.

if (e.NewElement != null)
{
	// progressbar and progressbar background color
	Control.ProgressDrawable.SetColorFilter(
		new PorterDuffColorFilter(
		Xamarin.Forms.Color.FromHex("#ff0066").ToAndroid(),
		PorterDuff.Mode.SrcIn));
}

 

Use the ProgressDrawable Property and set the ColorFilter to it as you wish… 😉 which will set the color theme to your Progress Bar , Progress Thumb, and the background bar…

Decoration 2 : Change only the Slider’s Thumb Color?

How about changing just the Progress Thumb’s color? Yes you may…

Look at that funky looking Progress Thumb! 😉

Code?

if (e.NewElement != null)
{
	// Set Progress bar Thumb color
	Control.Thumb.SetColorFilter(
		Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid(), 
		PorterDuff.Mode.SrcIn);
}

 

Android SeekBar (which is the native handler of Xamarin Forms Slider on Android) has the Thumb property which allows you to customize the appearance of the little thumbnail head of the Slider control as we have used above.

Next! 😀

Decoration 3 : Change progress background Color?

How about changing only the Progress Bar’s background color? As you can see below..

Look at the boring default progress bar’s background color vs the purple background color! 😉 pretty cool!

Here’s how you do it,

if (e.NewElement != null)
{
	//Set Background Progress bar color
	Control.ProgressBackgroundTintList 
           = ColorStateList.ValueOf(
            Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid());
	Control.ProgressBackgroundTintMode
           = PorterDuff.Mode.SrcIn;
}

 

Use the ProgressBackground property to set the TintList and the TintMode! 🙂

TADAA!

Decoration 4 : How about adding a secondary progress indicator?

Now we all have seen secondary progress indicators in progress bars, specially in online video stream players… 🙂 example take the Youtube player! 😉 So have you ever wanted to add such a cool feature to your Xamarin Forms Slider in Android? Let me show you how its done… 😉

Look how cool that is yeah! 😉

Alright let’s get into coding…

Now in Android we have this built in property called SecondayProgress which allows you to set a secondary progress value to your Slider or Seekbar as of native Android handler.

if (e.NewElement != null)
{
	// secondary progress value in Xamarin Forms units
	int secondaryProgressValue = 50;
	
	// secondary progress value in 
	// Android native Seekbar units
	int secondaryProgressValueInAndroidUnits =
	(int)((secondaryProgressValue - 
			((CustomSlider)Element).Minimum) /
	(((CustomSlider)Element).Maximum -  
			 ((CustomSlider)Element).Minimum) * 1000.0);

	// set the secondary progress value
	Control.SecondaryProgress = 
	secondaryProgressValueInAndroidUnits;
}

 

There you go, you can see that we are setting the SecondaryProgress value, but also take a closer look at the calculation that we are doing before setting it.

Now Xamarin Forms Slider and Xamarin Android Seekbar which is the handler for the Slider control, uses different value types or unit types for setting the Progress and the Secondary Progress values in native level. If we want to set the value from Xamarin Forms value units then we need to convert that value to Android Seekbar’s native values which is exactly what we are doing at the calculation. So basically we are setting the Xamarin Forms unit value according to the native units to Seekbar control.

Oh if you want to set the Secondary Progress from Xamarin Forms level then you can easily create a property in the CustomSlider class and use it down here in your Custom Renderer class 🙂 Imagination is the limit! 😉

Decoration 5 : May be change the Color of secondary progress indicator?

How about we spice it up by changing the color a little of the secondary progress? 😉

Look at that!

Time for coding…

Android Seekbar has this property called SecondaryProgressTintList and SecondaryProgressTintMode which allows you to achieve the above results and set the secondary progress color as you wish…

if (e.NewElement != null)
{
	//Set Seconday Progress bar color
	Control.SecondaryProgressTintList = 
	      ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid());
	Control.SecondaryProgressTintMode = 
	      PorterDuff.Mode.SrcIn;

	// secondary progress value in Xamarin Forms units
	int secondaryProgressValue = 50;
	
	// secondary progress value in 
	// Android native Seekbar units
	int secondaryProgressValueInAndroidUnits =
	(int)((secondaryProgressValue - 
	((CustomSlider)Element).Minimum) /
	(((CustomSlider)Element).Maximum - 
	 ((CustomSlider)Element).Minimum) * 1000.0);

	// set the secondary progress value
	Control.SecondaryProgress = 
		secondaryProgressValueInAndroidUnits;
}

 

And hey of course don’t forget to set the SecondaryProgress value while you’re at it!

Decoration 6 : I would call it Funky delight!

Alright, now all that being said, how about blending some of those different colors adding some funky delight-ness to the Slider? 😉

Well what I mean is, let’s try adding different color’s to Thumb, Progress Bar, Progress Bar background and Secondary Progress Bar!

Too much funky? I thought so!

How about these??? 😉

I know, I love playing with colors being a Visual oriented developer! 😀 lol

Your imagination is the limit fellas!

Here’s how you play around with the colors…

if (e.NewElement != null)
{
	// Different colors for ProgressBar components
	// Set Primary Progress bar color
	Control.ProgressTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#6200ea").ToAndroid());
	Control.ProgressTintMode 
		= PorterDuff.Mode.SrcIn;

	//Set Seconday Progress bar color
	Control.SecondaryProgressTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#b388ff").ToAndroid());
	Control.SecondaryProgressTintMode 
		= PorterDuff.Mode.SrcIn;

	//Set Progress bar Background color
	Control.ProgressBackgroundTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#b39ddb").ToAndroid());
	Control.ProgressBackgroundTintMode 
		= PorterDuff.Mode.SrcIn;

	// Set Progress bar Thumb color
	Control.Thumb.SetColorFilter(
		Xamarin.Forms.Color.FromHex("#311b92").ToAndroid(),
		PorterDuff.Mode.SrcIn);
}

 

Decide your flavor of colors and go crazy fellas! 😉

Decoration 7 : Remove Thumb Header may be?

Absolutely, check this out…

It’s pretty simply actually, simply set a Tranparent ColorDrawable to the Thumb property.

if (e.NewElement != null)
{
	// Hide thumb
	Control.SetThumb(
		new ColorDrawable(Color.Transparent));
}

 

Woot!

Decoration 8 : Let’s kick it up a notch!

Let’s add some more vibrant and complex customization to our Slider for Android! 🙂

How about throwing in some cool gradient effects…

So to achieve that, we shall be using Android native Styling with Drawables such as Shape, Gradients and so on.

We will create a native android xml Style file in your Resources/Drawable folder with the name “custom_progressbar_style.xml”

Here’s what you’ll be placing inside of it…

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

  <item android:id="@android:id/background">
    <shape>
      <corners android:radius="15dip" />
      <gradient
       android:startColor="#d9d9d9"
       android:centerColor="#e6e6e6"
       android:endColor="#d9d9d9"
       android:centerY="0.50"
       android:angle="270" />
    </shape>
  </item>
  
  <item android:id="@android:id/secondaryProgress">
    <clip>
      <shape>
        <corners android:radius="15dip" />
        <gradient
             android:startColor="#e6b3e6"
             android:centerColor="#ffcce0"
             android:endColor="#e6b3e6"
             android:centerY="0.50"
             android:angle="270" />
      </shape>
    </clip>
  </item>
  
  <item android:id="@android:id/progress">
    <clip>
      <shape>
        <corners android:radius="15dip" />
        <gradient
         android:startColor="#ff0066"
         android:centerColor="#ff00ff"
         android:centerY="0.50"
         android:endColor="#cc0052"
         android:angle="270" />
      </shape>
    </clip>
  </item>
  
</layer-list>

 

So to explain the above a little bit, we have created a Style layer-list which assigns the given styling items to the specific id’s of the SeekBar native control, such as the background, secondaryprogress, progress as you have noticed. Those drawable objects will replace the default styles of those segments in the SeekBar with these defined drawable objects.

First we are using a Shape drawable to to the Background property, which creates a gradient layer with the given colors and angle for creating a gradient effect! Also we are setting a radius value to corner so that the corners will be curved nicely.

Next for the Progress and the SecondaryProgress properties we are creating a similar Shape gradient as before but we are clipping it according to the given values of each of them.

if (e.NewElement != null)
{
	// Set custom drawable resource
	Control.SetProgressDrawableTiled(
	Resources.GetDrawable(
	Resource.Drawable.custom_progressbar_style,
	(this.Context).Theme));

	// Hide thumb to make it look cool lol
	Control.SetThumb(new ColorDrawable(Color.Transparent));
}

 

There’s how you set it in the custom renderer level, simply call the SetProgressDrawableTiled() method by passing the custom style of what we created above.

Also I have disabled the Thumb, just to make it look cooler. Its up to you though.

If you want to do more extensible customization like above and may be preserve the Thumb view and style that as well? then refer to this stackoverflow article: http://stackoverflow.com/questions/16163215/android-styling-seek-bar

Additionally you could have bitmap images or nine patch images as drawables to styling and so may other stuff.

Now this is like the holy grail.. where as you can see with Android you get full flexibility for any kind of complex customization!

Its only limited by your imagination! 😉

WooT! 😀

Decoration 9 : Can I reduce the above overridden Height?

So you’re worried of the height after setting the custom styling drawables as above? simply reduce the HeightRequest value in your Xamarin Forms code for our custom Slider view.

Right after we set the Custom ProgressDrawable styles in the renderer level, it overrides the Height property of native SeekBar  that’s assigned from Xamarin Forms level for each of those sub-views (ProgressBar, SecondaryProgressBar and Background sub views), so they expands themselves to the fullest as possible with the new Drawable objects.

<local:CustomSlider HeightRequest="7" WidthRequest="350"  HorizontalOptions="Center"
        Minimum="0" Maximum="100" />

 

So the above should give you control over the Height issue!

Or else you could set the dip IntrinsicHeight values in your XML style drawables itself as well (something extra)! 😉

Decoration 9 : Can I  have the above cool-ness programmatically without resources?

So you don’t like to deal with Android Resources and creating the Style XMLs and stuff?

Oh sure, no worries! but you will have to do a little bit of work to get the above simple XML Styling into pure code generated objects!

Let me begin by giving credit to this example written in Java which I found while I was in the same situation: FlatUI/FlatSeekBar.cs

So let’s see how we could create Drawable Style objects in C# code!

Now keep in mind all the Drawable objects we used in our XML file “custom_progressbar_style.xml” has their own programmatical counterparts such as Shape, Gradient and Clip by the names as ShapeDrawable, GradientDrawable, and ClipDrawable and so on likewise.

So we can convert any given XML style to a C# generated style drawable. (any native Android developer should be well aware of this)

So let’s do something similar! 😉

So we are going to create our own Drawable objects and set them to the sub-views of our Slider control for Android, just like how we did with the XML styling, but this time programmatically. Here is how it will look like…

There you haveit, let’s see how we did this…

if (e.NewElement != null)
{
	// Setting drawable styling programatically

	// progress
	var progress = new PaintDrawable(Color.Red);
	progress.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	progress.SetIntrinsicHeight(
		(int)DpToPixels(this.Context,10));
	var progressClip = 
		new ClipDrawable(progress, GravityFlags.Left,
		ClipDrawableOrientation.Horizontal);

	// secondary progress
	var secondary = new PaintDrawable(Color.Gray);
	secondary.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	secondary.SetIntrinsicHeight(
		(int)DpToPixels(this.Context, 10));
	var secondaryProgressClip = 
		new ClipDrawable(secondary, GravityFlags.Left, 
		ClipDrawableOrientation.Horizontal);

	// background
	PaintDrawable background = new 
                 PaintDrawable(Color.LightGray);
	background.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	background.SetIntrinsicHeight(
		(int)DpToPixels(this.Context, 10));

	// retrieve LayerDrawable reference of the SeekBar control
	LayerDrawable layeredDrawableReference 
		= (LayerDrawable)Control.ProgressDrawable;
		
	// apply our custom drawable objects to the 
	// given sub-views through their IDs
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.Background, background);
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.Progress, progressClip);
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.SecondaryProgress, 
                  secondaryProgressClip);
}

 

So basically we are creating our our Drawable objects programatically, in this case PainDrawable objects and giving them different styling values such as Radius, Clipping, IntrinsicHeight and so on.

And then at the end we are going to retrieve the references for the sub-views of our native SeekBar in Android which is the after-rendering counterpart of Xamarin Forms Slider as I mentioned at the beginning. This is going to be a LayerDrawable object, which is going to allow us to set our own custom Drawable objects to each drawable layer by their IDs.

As you can see we are calling the SetDrawableByLayerId() on our LayerDrawable object and passing in the each sub-view reference and custom drawable objects we want to set to them. 😀

Now keep this in mind, here you could have any kind of drawable objects to create your custom drawable styling just like you previously did with GradientDrawable in XML style, have the exact same beautiful visual result rendered programatically! 🙂

That’s it…

Well fellas that’s it for now, well at least that’s all I came across while I was playing around with my Custom Renderer for Xamarin Forms Slider on Android! 😀

Enjoy and share!

CHEERS!

Advertisements

FormsAppCompatActivity is not calling OnOptionsItemSelected Xamarin Android…

So have you Sub-classed your MainActivity from FormsAppCompatActivity which is also the default Parent Class for MainActivity in Xamarin Forms Android project? but you can’t get a hit on the OnOptionsItemSelected override?

Welcome to another flash post!

Recently I tried..

So recently I tried to override the navigation bar Back button click on Android in one of my Xamarin Forms applications.

but Unfortunately…

So one way to handle this is by overriding the OnOptionsItemSelected method in MainActivity, which is the Single Activity that all our Xamarin Forms Views get’s laid upon. But unfortunately I wasn’t able to get a hit on the above override method.

then I noticed…

So this project solution was created on Visual Studio with Xamarin version 4.2.2.11, where as I noticed that the MainActivity was sub-classing from the FormsAppCompactActivity instead of good old FormsApplicationActivity which was the previous parent class for MainActivity.

No sense…

Since it did not make sense I turned to the Xamarin Forums, and lucky enough I found this thread, where few others were also experiencing the same issue.

https://forums.xamarin.com/discussion/comment/218663#Comment_218663

Reason? Probably…

So according to the forums, it appears to be some missing bug in Xamarin Android version, where as the Android Toolbar doesn’t get referenced to the Activity. Where as since we are using FormsAppCompactActivity as the base, the Toolbar in action is the Android.Support.V7.Widget.Toolbar, not the good old Android.Widget.Toolbar, which for some reason doesn’t get attached to the Activity.

Solution…

Well if you had gone through the above forum you may have found the solution already… Basically we just need to set the Action Bar reference in the Activity in your OnCreate() method.. 😉

Android.Support.V7.Widget.Toolbar toolbar 
	= this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);

 

or if I’m to share my MainActivity…

public class MainActivity : FormsAppCompatActivity
{
	protected override void OnCreate(Bundle bundle)
	{
		TabLayoutResource = Resource.Layout.Tabbar;
		ToolbarResource = Resource.Layout.Toolbar;

		base.OnCreate(bundle);

		global::Xamarin.Forms.Forms.Init(this, bundle);
		LoadApplication(new App());
		
		Android.Support.V7.Widget.Toolbar toolbar 
			= this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
		SetSupportActionBar(toolbar);
	}
}

 

Well there you have it! Solved! 😀

Cheers!

DpToPixels and PixelsToDp for Xamarin Android…

We all know the sea of Android devices consists of different kinds of Screen Densities, this is why in Android programming we always refer to Density Pixels instead of actual Pixels, so that we could use the exact value of Pixels that best catered for the given Screen Density of the  physical device.

Now this is going to be another flash post, where I share stuff in sweet and short form without any spoon feeding! 😛

Straight on Point:

(px) Pixels –

corresponds to actual pixels on the screen.

(dp or dip) Density-independent Pixels –

an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both “dip” and “dp”, though “dp” is more consistent with “sp”.

Extracted from: Android Developer Documentation

Well now when it comes to Xamarin Android development this is the same scenario, but the way we actually use it code could be a bit tricky.

So here I’m sharing the two Helper methods I came up with for the conversion inbetween actual Pixels and Device Independ Pixels value and Device Independ Pixels to actual Pixels value… 😀

/// <summary>
/// Device Independent Pixels to Actual Pixles conversion
/// </summary>
/// <param name="context"></param>
/// <param name="valueInDp"></param>
/// <returns></returns>
public static float DpToPixels(Context context, float valueInDp)
{
	DisplayMetrics metrics = context.Resources.DisplayMetrics;
	return TypedValue.ApplyDimension(ComplexUnitType.Dip, valueInDp, metrics);
}

/// <summary>
/// Actual Pixels to Device Independent Pixels conversion
/// </summary>
/// <param name="context"></param>
/// <param name="pixelValue"></param>
/// <returns></returns>
public static int PixelsToDp(Context context, float pixelValue)
{
	var dp = (int)((pixelValue) / context.Resources.DisplayMetrics.Density);
	return dp;
}

 

There you have it!

Enjoy! 😀

I encountered “GenerateJavaStubs” task failed unexpectedly in Xamarin Android

I encountered this during error during a compilation of one of my Xamarin Android apps. After installation of a new 3rd party library, I tried compiling my project, but BOOM! this happened!

What happened ?

So I took a little look-around. Well my project solution is a multi-hierarchical project, where as I have an Android Library, Core Library, and Client Project App referenced in a hierarchical manner .

So what has happened was, after some third party library installation, a duplicate MainApplication class had been generated somehow. 😮

Solution ?

Remove the duplicate  MainApplication class in your project, hence Android requires only one point to fire up. 😉

Make sure you don’t have duplicate MainApplication classes that derives from Application base class in your Xamarin.Android project. Specially if you have a hierarchical project implementation, such as a Android Library project attached to your Main application project.

In such cases make sure you maintain only one MainApplication class that derives from Application base class, in either of your projects. 😀

TADAAA! 😀

Xamarin Android deployment error INSTALL_FAILED_ UPDATE_INCOMPATIBLE

While your trying to build and deploy your Xamarin Android solution, have you ever encountered an error such as,

Deployment failed because of an internal error: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]

or with a similar error code as below?

[INSTALL_FAILED_DUPLICATE_PERMISSION]

If so, I should let you know, I’ve been there too!

This is usually because the last time you uninstalled your app from the emulator or device, you haven’t done it properly or something may have gone wrong during the uninstallation and some chunks of the old package is still lying around the system, therefore it preventing the reinstallation of your new package.

As the solution?

Therefore we need to completely uninstall the package manually through the adb command.

adb uninstall my.package.id

You must replace the my.package.id with your Xamarin Android app’s id.

And try again! Should be good to go! 😉

Is your Visual Studio stuck at, Emulator is already running?

So few days back after doing a fresh installation on my WIndows 10 laptop, and installing Visual Studio, I tried running a Xamarin Forms project, with the Visual Studio Android Emulator.

The project was successfully building itself, and the Visual Studio Android Emulator also started running successfully, but then the build process was on a hang state after the Emulator started running. Specifically the build log was on a hang state after “Emulator is already running” step, as I saw in the output log in VS.

So after Googling a while I figured out the problem thanks to wasting a bunch on hours on google search and forums, since many others were also having the same issue.

So let me post the solution for you right here.

Cause?

You must keep in mind that my project was building fine, and the Emulator also started running successfully and booted up itself. I was having a already built solution and up and running Emulator, but the VS couldn’t connect to the Emulator.

The cause for this is Visual Studio debugger was unable to connect to the started Emulator through the ADB (Android Debug Bridge).

This is due a wrong registry entry in the system, where as Visual Studio is looking to start up the ADB and connect to it, in order to connect to the Emulator, but due to this wrong registry entry, VS is unable to find the path to ADB, to start it up.

This is very well explained in this Visual Studio troubleshoot article:

https://msdn.microsoft.com/en-us/library/mt228282.aspx?f=255&MSPPError=-2147217396#ADB

This seem to be happening by default with fresh installations of VS lately, where as the Android SDK installation path in the above registry entry doesn’t seem to be matching with the actual SDK installation location in our system, which is probably done by default when installing Visual Studio 2015.

Solution!

So yeah as the article explains we just have to update the registry entry with the accurate path to the Android SDK installation in our system, so that Visual Studio can start up ADB to connect to the Emulator.

Step1 : Copy the actual Android SDK installation path

to find the actual Android SDK path in your system, that is referred by Visual Studio, go to the top tool bar of Visual Studio, and open the Android SDK Manager as shown below.

capture-3

If you did the default Visual Studio installation with the Cross-Platform mobile dev tools, then your path location should also look similar as above.

Copy that path, or type the same exact path on Run command and open the folder and copy the full path from there.

Step2 : Update the invalid registry entry

Open registry editor, by “regedit” in Run window and navigate to the following Registry.

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools

Now open the Path registry key and change the value with the above Android SDK path which you copied earlier.

capture-2

Well, that’s it.

There goes the solution. Now you should close the Emulator and Visual Studio and reopen your solution, hit F5! you’re all good! 😀

Cheers!

An infamous(or not?) fact(something important?) about Xamarin Forms Navigation in Android…

Xamarin Forms uses a very neat and simplified Navigation Architecture which can be easily justified among Android, iOS and WinPhone mobile platforms under common grounds.

Xamarin Forms Navigation

Alright, now this is not an article about Xamarin Forms Navigation article, as it is very well explained in Xamarin official documentation. If you want to go check it out right now before you get into this article. https://developer.xamarin.com/guides/xamarin-forms/user-interface/navigation/hierarchical/

Now the way Xamarin Forms handles this navigation during the actual runtime, specifically in native levels are different for each mobile platforms. Of course they have to somehow map Xamarin Forms Navigation paradigm to the Native app navigation paradigm, which is extremely complex and Xamarin has done a great job so far. 😀

Why is Navigation so Important?

Navigation plays a huge part in your Mobile Application development, specially when it becomes more complex when you need to implement deeper customisations to your cross platform app.

So when we get down to complex customisations related to your Navigation, it is very important to be aware of the underlying mechanics of the platform.

Hence with Xamarin Forms, we are dealing with a cross-platform situation, where it is very crucial that we pay attention to three different mobile platforms, and how their navigation is actually handled in Xamarin Forms.

Xamarin has done a great job in handling a common cross-platform navigation pattern, and faded out the Native-compatibility mechanics to the background, to the point a developer doesn’t really have to pay any attention to it. So kudos Xamarin! 😉

Recently I…

So the reason I’m writing this article is because, recently I came across a situation where I had to pay detailed attention for Xamarin Forms Navigation and how it actually handles it in native execution. 🙂

And there’s something very interesting I spotted in how Xamarin Forms handles Navigation in Android runtime..

So I thought of sharing it with everyone, hence most developers doesn’t seem to be aware of this.

Specially amongst the fresh developers of the Xamarin Community, where a lot of developers assume Xamarin Forms follows everything exactly as the Native Framework patterns and properties, which is not actually accurate and they have taken some unique (or may be different) approaches for mapping Native stuff to the Xamarin Forms level, which are quite out of the box. So you need to pay a good attention to their details when you are dealing with complex implementations in Xamarin Forms.

So what’s the big deal I found with Xamarin Forms Navigation in Android ?

Xamarin Forms Navigation in Android?

Now when it comes to handling Xamarin Forms Navigation in Android run time, I noticed something very interesting, which I should blame myself for not paying any attention way earlier for this aspect. However…

If you’re familiar with Native Android development, the standard pattern of how we navigate in-between Activities and Fragments, how the activity lifecycle is handled so on and so forth yeah? (Nope, I’m not gonna get into the details of Android Navigation pattern in this article, if you aren’t aware, please stop reading this article and Google about it, then you may get back here… other wise you might get confused!)

Now have you ever thought how Xamarin Forms actually handles this complex Android Navigation Pattern? And actually map the Xamarin Forms Navigation paradigm to the Native Android Execution?

Now this is where it gets interesting…

Go on to this link which explains the NavigationPage (the page that manages the navigation) of Xamarin Forms, and read the REMARKS! READ IT!

https://developer.xamarin.com/api/type/Xamarin.Forms.NavigationPage/

Let me quote it,

“Note that on the Android platform, INavigation operations do not generate activity lifecycle notifications. For each Page that you push or pop, the Android implementation of NavigationPage simply adds or removes the content of the page to or from a single activity.”

Interesting right?

Now I did some more research about it, and came across more interesting facts.

At Xamarin Evolve 2014…

Watch this Youtube clip where an attendee asks Jason Smith about the Navigation pattern of Xamarin Forms in Android.

Attendee: I was curious why you designed the Xamarin Forms Android to be a Single Activity as opposed to Multiple Activity?

Jason: Couple of minor considerations I guess. At the time Fragments weren’t fully back ported when we started the project. So we couldn’t actually target Fragments, which was really annoying. And Google was advocating the Single Activity approach and on top of that Navigations Paradigms of Activity didn’t fully map to the Xamarin Forms Navigation Paradigm.

Furthermore from Jason Smith…

So I found a post in Xamarin Forms Community Forum  where Jason Smith has commented regarding the navigation further more a s follows…

https://forums.xamarin.com/discussion/17668/running-xamarin-forms-as-one-single-activity-vs-performance-design

TheRealJasonSmith [Jason Smith]

“Xamarin.Forms pre-dates the backporting of Fragments on Android, however it is written in a fashion similar to how fragments work. The Views we add/remove from the view hierarchy are fully cleaned up and disposed of when they go away. This works around the standard issue people had with single activity apps where all the views would stick around eating lots of memory.

Even if you as the user pre-allocate all of your Xamarin.Forms views, we do not realize them into actually android objects until they are needed on screen. We then will remove and dispose those same objects dynamically when they are no longer needed. This means that you should not be paying a significant memory overhead, even if you are not mindful of this yourself.”

So now what does this all tell us?

So after all these findings what is the conclusion we could come to?

In Native Android Development…

Untitled-3

When we develop Native Android application we usually use the standard Multiple Activities approach to propagate the pages and to navigate in between them, and sometimes we throw in some Fragments here and there as needed for memory saving and re-usability.

There is also an approach called “Single Activity Architecture” approach where you maintain only one activity and render all the pages on top of it in Native Android development.

Xamarin Forms Navigation in Android?

Untitled-2

Short and sweet Xamarin Forms does not follow the same standard multiple activity pattern in Android

Instead,

Xamarin Forms uses a unique Single Activity Architecture based pattern in Android which is similar to the use of Fragments, but with a better management of memory with its approach…

As with all our findings this is quite a unique approach that Xamarin Forms has implemented under the hood for Android. Which is very important to keep in mind when you get down to complex implementation of Xamarin Forms in Android.

Advantages and also Disadvantages ?

This gives many advantages and also disadvantages for us developers. Advantages such as good memory management, ease of navigation, instead of dealing with Activities and Fragments directly.

But this also brings many disadvantages which I had struggled in great deals with in Xamarin Forms complex implementations for Android, such as management of a custom ActionBar across your views, adding custom page transition animations for pages, unpleasant UX behavior when hiding ActionBar and so on.

But then again, there is always a way to solve problems in programming. 🙂

That’s it… 🙂

Well there you go, hope this clears any confusion anyone had just like I did sometime back… 🙂 And if you weren’t aware of this before, now you know how to handle stuff when it’s in need during your Xamarin Forms mobile development.

Cheers! 😀

Handling Page Transition Animations in Xamarin Android

Alright let’s get straight to point, You want to add some fancy transition animations to your Pages in your Xamarin Android app ? more specifically when the user navigates through the app between the pages, you need to add some nice animations for the page transition ? 😉

I came across this situation and I couldn’t find any articles on it, therefore after solving my issue, I decided to write my own to share my experience.

Yep here’s how you do it in Xamarin Android.. 😉

In Android we could define the type of transition animation that we need to add to our pages, both when we are opening the page and exiting the page, whereas we could pass those defined properties to the page Activity included in the Bundle object. 😀

So that’s what we are going to do.

As you can see below I have created a custom animation for the page MyPageActivity whereas this certain page would use the defined animations when during it’s opening and exiting executions.

We define the animation and include them in a bundle to pass into the StartActivity method, in order to deliver it to the opening Activity.

// Adding the transition animation to the ActivityOptions and include them in a Bundle
Bundle animationBundle = ActivityOptions.MakeCustomAnimation(this, Resource.Animation.abc_fade_in, Resource.Animation.abc_fade_out).ToBundle();

// Pass on the Bundle object to the StartActivity method 
this.StartActivity(new Intent(this, typeof(MyPageActivity)), animationBundle);

 

Above I have created the animation using the existing default animation types, you could add your own custom animations as you wish just as above, whereas you just have to give the resource ID for the custom animation of your’s. 🙂

Well, hope that was helpful… 🙂

Sorry this was a short post without any screenshots, going through some crazy busy times at office, barely having any time to blog 😦

Cheers! Stay Awesome! 😀

 

Load Image Resources by Name in Android Xamarin

It’s no secret that we can not access Image Resources by name in Android specially in code behind, whereas you need to pass in the Resource ID, or access it through the Resource Manager.

There was this one time I wanted to access some Image Resources by name, I mean why not? If I’m aware of the name of the resource why can’t I access it with the file name instead of looking for a resource ID. lol 😛 Well actually I had some serious requirement to deal with regarding retrieving the Image Resource by name in one of my projects.

So as usual here I am sharing the code implementation, incase if any of you are going through the same issue, here’s how I implemented it. 😉

How to ?

Well it’s the same as retrieving the Resource with the Resource ID, but instead we need to find the Resource ID by the name of the image.

In Xamarin Android we have access to the Resource.Drawable which contains all the Resource ID along with their names, so what we need to do is search through its public field by the specific file name of our Image Resource.

string imagefileName = "testimage.jpg";
// Remove the file extension from the image filename
imagefileName = imagefileName.Replace(".jpg","").Replace(".png","");

// Retrieving the local Resource ID from the name
int id = (int)typeof(Resource.Drawable).GetField(imagefileName).GetValue(null);

 

As you can see above first of all we remove the file extension from the filename of the image we want to load and we access the Resource.Drawable public fields to search for the name of the image resource, and finally retrieve the Resource ID.

Now as we have the Resource ID of the image we can retrieve it from our Resources as Bitmap Image.

// Converting Drawable Resource to Bitmap
var myImage = BitmapFactory.DecodeResource(Forms.Context.Resources, id);

 

There you can see I’m using the BitmapFactory to convert the Resource to Bitmap Image, thereby now we can use our Bitmap image as anyways we want. 😀 If you need to check whether the ID has been found you could add an IF condition and check whether the ID value is 0 or not

So here’s the full code Implementation…

string imagefileName = "testimage.jpg";
// Remove the file extention from the image filename
imagefileName = imagefileName.Replace(".jpg","").Replace(".png","");

// Retrieving the local Resource ID from the name
int id = (int)typeof(Resource.Drawable).GetField(imagefileName).GetValue(null);

// Converting Drawable Resource to Bitmap
var myImage = BitmapFactory.DecodeResource(Forms.Context.Resources, id);

 

There you have it folks ! 😀 Now you may go crazy with it 😛 !

Stay Awesome! 😀

Cheers!

Auto spanning LinearLayout for Xamarin Android

Ever wanted to have a LinearLayout to auto span through the screen, more over take the whole screen width and expand itself with equal spaces in between the elements ? Well I know have. 😉

So here’s another short and sweet code sharing post! 😀

So what happened ?

Well anyhow usually during such above scenarios the first thing that come’s to my mind is the RelativeLayout in Android, so I went ahead and implemented it, whereas I had two buttons in the corner and a textview in the middle, I just needed it to be auto spanned the whole screen width and take equal space in between. I managed to create the design as expected but weirdly enough, the click events of the buttons weren’t working, and literally the I wasn’t able to click on the buttons, as if RelativeLayout was hovering over the buttons.

Oh yes I tried enabling the Clickable property of RelativeLayout as well, even the Focus enable property, but nothing worked!

LinearLayout for the rescue!

So helplessly I forced myself to change to LinearLayout, and lucky enough I managed to get it done after a few hours of playing around lol! 😀 It still doesn’t make any sense why the buttons weren’t clickable inside the RelativeLayout. O_o However I’m glad I figured out a workaround with the LinearLayout.

So anyways if any of you run into such situation, or looking to implement LinearLayout for a similar situation, here  is the code XML code I used for my layout. 😉

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:orientation="vertical" />
  <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button 1" />
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:orientation="vertical" />
  <Button
      android:id="@+id/button2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button 2" />
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:orientation="vertical" />
  <Button
      android:id="@+id/button3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button 3" />
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:orientation="vertical" />
  <Button
      android:id="@+id/button4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button 4" />
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:orientation="vertical" />
</LinearLayout>

 

So basically what I have done is, added empty LinearLayouts in between the buttons and assign an equal weight to the layout property. This will make the layout span across the full screen width, taking equal spaces in between, despite of Landscape mode Portrait mode. You could even assign different spacing in between the buttons, which will get automatically maintained among Landscape and Portrait modes. 🙂

Here’s how it actually looks like…

Screen Shot 2016-02-11 at 4.09.17 PM Screen Shot 2016-02-11 at 4.09.37 PM

 

WOOT! WOOT! 😀 there you go ! 😉 Enjoy!

Stay Awesome fellas!