Category Archives: Android

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! 😀

Advertisements

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!

Listening to the Layout on Xamarin Android PageRenderer! (LayoutListener)

So when you create a Custom Renderer for your Xamarin Forms ContentPage, on Android, sometimes you have to tap into the Android Layout changes on your current page.

For instances like, Orientation changes, Keyboard visibility changes on Android and so on.

This is done by Adding a Layout Listener to our Layout’s ViewTree. 🙂 Confusing? Let’s get to work!

Create a Layout Listener…

First let’s create our Layout Listener, the guy who get’s the call back when the Layout Changes on the ViewTree of our Layout.

public class CustomLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
{
	public void OnGlobalLayout()
	{
		// do whatever the stuff you wanna do here
	}
}

 

We derive to from the IOnGlobalLayoutListener interface, where as you need to implement its OnGlobalLayout() method which get’s the call back when a Layout change occurs.

Add the Listener to the ViewTree…

Next add it to the ViewTreeObserver of your Layout.

[assembly: ExportRenderer(typeof(CustomContentPage), typeof(CustomContentPageRenderer))]
namespace WhateverYourNamespace
{
    public class CustomContentPageRenderer : PageRenderer
    {
        protected override async void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
			var rootView = CrossCurrentActivity.Current.Activity.Window.DecorView.RootView;
			rootView.ViewTreeObserver.AddOnGlobalLayoutListener(new CustomLayoutListener());
		}
	}
}

 

Since I implemented this on a Xamarin Forms Custom Renderer, first I have gained access to the current Activity’s RootView (from a 3rd party library CurrentActivityPlugin) and then I have added my listener to the ViewTreeObserver of my root view. 😀

TADAA! 😀

but you could also…

Oh well good things comes to those who wait.. lol Xamarin Android provides you an event called GlobalLayout where you could also directly subscribe to Layout changes without having to implement your own listener.

rootView.ViewTreeObserver.GlobalLayout += (sender, args) =>
{
	// do whatever the stuff you wanna do here
}

 

Oh well it depends on your implementation requirement though.

Anyways there you have it! 😀

Enjoy!

An improved ScrollView control for Xamarin Forms by me, myself and I…

Alright now when it comes to the default Xamarin Forms ScrollView, its pretty much generic and limited with the simple common attributes and behaviours, and it does not deliver any specific “cool” features with it.

What’s so cool about it?

So I thought of creating my own Custom ScrollView for Xamarin Forms using Custom Renderers, which would include the following awesome features,

Bouncy Effect – Yeah you gotta admit, the bounce effect of a native scrollview is pretty fun to play with, in a User’s perspective. So I thought of enabling this feature in my custom ScrollView even when the Child Element doesn’t exceeds the ScrollView boundaries… 😉
(PS: this effect is interpreted in native Android and iOS differently)

Disabling and Enabling Horizontal and Vertical Scroll Indicators – Now sometimes these scroll bar indicators are useful but there are times which we want to hide them, as it might look ugly on the UI in certain cases. So yeah let’s have some control over it shall we? 😀

Background Image – Of course who wouldn’t like a background Image on a Scroll view eh! 😉 Well to be specific we are going to add a Fixed Background Image for the ScrollView. And note that this background Image would be fixed, and will not be scrolling with the Content of the ScrollView. (I will do another post to enable that feature).

Yes behold, me, myself and I presenting the “BloopyScrollView” why the name “BloopyScrollView”? I don’t even know. lol 😛

Implementation

Alright let’s go ahead and create our Custom ScrollView Control in the PCL project. Along with the following properties, so that we could have direct control over the above said behaviours.

Alright now expect this to be longer, since I have added the properties as Bindable Properties, so you could use them in any MVVM scenario with ease. 😀

namespace WhateverYourNamespace
{
    public class BloopyScrollView : ScrollView
    {
        public static readonly BindableProperty IsHorizontalScrollbarEnabledProperty =
        BindableProperty.Create(
            nameof(IsHorizontalScrollbarEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            false,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Horizontal scrollbar visibility
        /// </summary>
        public bool IsHorizontalScrollbarEnabled
        {
            get { return (bool)GetValue(IsHorizontalScrollbarEnabledProperty); }
            set { SetValue(IsHorizontalScrollbarEnabledProperty, value); }
        }


        public static readonly BindableProperty IsVerticalScrollbarEnabledProperty =
        BindableProperty.Create(
            nameof(IsVerticalScrollbarEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            false,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Vertical scrollbar visibility
        /// </summary>
        public bool IsVerticalScrollbarEnabled
        {
            get { return (bool)GetValue(IsVerticalScrollbarEnabledProperty); }
            set { SetValue(IsVerticalScrollbarEnabledProperty, value); }
        }


        public static readonly BindableProperty IsNativeBouncyEffectEnabledProperty =
        BindableProperty.Create(
            nameof(IsNativeBouncyEffectEnabled),
            typeof(bool),
            typeof(BloopyScrollView),
            true,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Native Bouncy effect status
        /// </summary>
        public bool IsNativeBouncyEffectEnabled
        {
            get { return (bool)GetValue(IsNativeBouncyEffectEnabledProperty); }
            set { SetValue(IsNativeBouncyEffectEnabledProperty, value); }
        }


        public static readonly BindableProperty BackgroundImageProperty =
        BindableProperty.Create(
            nameof(BackgroundImage),
            typeof(ImageSource),
            typeof(BloopyScrollView),
            null,
            BindingMode.Default,
            null);
        /// <summary>
        /// Gets or sets the Background Image of the ScrollView
        /// </summary>
        public ImageSource BackgroundImage
        {
            get { return (ImageSource)GetValue(BackgroundImageProperty); }
            set { SetValue(BackgroundImageProperty, value); }
        }
    }
}

 

There we go IsHorizontalScrollbarEnabled, IsVerticalScrollbarEnabled to disable/enable Horizonal and Vertical Scrollbars.

IsNativeBouncyEffectEnabled to control the Native Bouncy effect.

BackgroundImage to set the ImageSource for the ScrollView’s background Image. And make sure to provide a proper image for this hence we will be resizing the given image in our native renderer level to fit to the background of the ScrollView.(You will see in the next steps below)

Alright let’s head over to creating the Custom Renderers associated with our BloopyScrollView.

Something to keep in mind…

So if you’re a frequent reader of my blog, you may remember sometime ago I created an Extention class for handling Xamarin Forms Images in Native code level: https://theconfuzedsourcecode.wordpress.com/2016/12/12/an-awesome-image-helper-to-convert-xamarin-forms-imagesource-to-ios-uiimage-or-android-bitmap/

Why I’m bringing this up, is because we are going to be needing it for this project. You ask why? Because we need to convert the above BackgroundImage, which is of type Xamarin Forms ImageSource.

So we need to convert that ImageSource to native UIImage or Bitmap image respectively in our Custom renderer levels. 😉

So go ahead and grab that code real quick and add it to your Native Projects. 😀

iOS Implementation

Now let’s create the Custom Renderer for the Control in Xamarin.iOS project.

[assembly: ExportRenderer(typeof(BloopyScrollView), typeof(BloopyScrollViewRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class BloopyScrollViewRenderer : ScrollViewRenderer
    {
        private UIImage _uiImageImageBackground;

        protected override async void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            this.ShowsVerticalScrollIndicator = ((BloopyScrollView)e.NewElement).IsVerticalScrollbarEnabled;
            this.ShowsHorizontalScrollIndicator = ((BloopyScrollView)e.NewElement).IsHorizontalScrollbarEnabled;

            if (e.NewElement != null)
            {
                if (((BloopyScrollView)e.NewElement).IsNativeBouncyEffectEnabled)
                {
                    this.Bounces = true;
                    this.AlwaysBounceVertical = true;
                }

                if (((BloopyScrollView)e.NewElement).BackgroundImage != null)
                {
                    // retrieving the UIImage Image from the ImageSource by converting
                    _uiImageImageBackground = await IosImageHelper.GetUIImageFromImageSourceAsync(((BloopyScrollView)e.NewElement).BackgroundImage);
                }

                ((BloopyScrollView)e.NewElement).PropertyChanged += OnPropertyChanged;
            }
        }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
        {
            if (propertyChangedEventArgs.PropertyName == BloopyScrollView.HeightProperty.PropertyName)
            {
                // check if the Width and Height are assigned
                if (((BloopyScrollView)sender).Width > 0 & ((BloopyScrollView)sender).Height > 0)
                {
                    // resize the UIImage to fit the current UIScrollView's width and height
                    _uiImageImageBackground = ResizeUIImage(_uiImageImageBackground, (float)((BloopyScrollView)sender).Width, (float)((BloopyScrollView)sender).Height);

                    // Set the background Image
                    this.BackgroundColor = UIColor.FromPatternImage(_uiImageImageBackground);
                }
            }
        }

        // We need to override this to have the background image to be fixed
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);
        }

        // Resize the UIImage
        public UIImage ResizeUIImage(UIImage sourceImage, float widthToScale, float heightToScale)
        {
            var sourceSize = sourceImage.Size;
            var maxResizeFactor = Math.Max(widthToScale / sourceSize.Width, heightToScale / sourceSize.Height);
            if (maxResizeFactor > 1) return sourceImage;
            var width = maxResizeFactor * sourceSize.Width;
            var height = maxResizeFactor * sourceSize.Height;
            UIGraphics.BeginImageContext(new CGSize(width, height));
            sourceImage.Draw(new CGRect(0, 0, width, height));
            var resultImage = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
            return resultImage;
        }
    }
}

 

Inside the method we are assigning the relevant properties of our BloopyScrollView to the native control properties.

The UIScrollView which is associated with the Xamarin Forms ScrollView has the following native properties:

  • ShowsVerticalScrollIndicator: Make the vertical scrollbar visible or hidden
  • ShowsHorizontalScrollIndicator: Make the horizontal scrollbar visible or hidden
  • Bounces: Always enable the native bounce effect on iOS UIScrollView
  • BackgroundColor: Allows to set the background color for the UIScrollView or set an Image as a pattern

Also you may have noted that we are converting our Image Source BackgroundImage to a UIImage using our extension.

And then when the Height and Width are set to the Control, we are resizing the Image to fit those properties and setting that as the Background of the UIScrollView through the UIColor.FromPatternImage() which allows us to set the image as a pattern throughout the canvas of the UIScrollView.

the strange tale of getting the UIScrollView’s Fixed background in Xamarin… :O

Notice that we are overriding the Draw(CGRect rect) method, this is to have the UIScroll Background Image to be fixed within the boundaries, and not to be spanned across the Content area.

Because usually if we set the BackgroundColor property, it will span across the Content area, but strangely if we override the Draw() method, BackgroundColor would only be contained within UIScrollView’s boundaries, without spanning across the Content area. This is something I figured out while playing around with the above implementation. 😀

Alright let’s jump into Android… 😀

Android Implementation

Now let’s create the Custom Renderer for the Control in Xamarin.Android project.

[assembly: ExportRenderer(typeof(BloopyScrollView), typeof(BloopyScrollViewRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class BloopyScrollViewRenderer : ScrollViewRenderer
    {
        private Bitmap _bitmapImageBackground;

        protected override async void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            this.VerticalScrollBarEnabled = ((BloopyScrollView)e.NewElement).IsVerticalScrollbarEnabled;
            this.HorizontalScrollBarEnabled = ((BloopyScrollView)e.NewElement).IsHorizontalScrollbarEnabled;

            if (((BloopyScrollView)e.NewElement).IsNativeBouncyEffectEnabled)
            {
                this.OverScrollMode = OverScrollMode.Always;
            }

            if (((BloopyScrollView) e.NewElement).BackgroundImage != null)
            {
                // retrieving the Bitmap Image from the ImageSource by converting
                _bitmapImageBackground = await AndroidImageHelper.GetBitmapFromImageSourceAsync(((BloopyScrollView)e.NewElement).BackgroundImage, this.Context);

                // resize the Bitmap to fit the current ScrollView's width and height
                var _resizedBitmapImageBackground = new BitmapDrawable(ResizeBitmap(_bitmapImageBackground, this.Width, this.Height));

                // Set the background Image
                this.Background = _resizedBitmapImageBackground;
            }
        }

        // Resize the Bitmap
        private Bitmap ResizeBitmap(Bitmap originalImage, int widthToScae, int heightToScale)
        {
            Bitmap resizedBitmap = Bitmap.CreateBitmap(widthToScae, heightToScale, Bitmap.Config.Argb8888);

            float originalWidth = originalImage.Width;
            float originalHeight = originalImage.Height;

            Canvas canvas = new Canvas(resizedBitmap);

            float scale = this.Width / originalWidth;

            float xTranslation = 0.0f;
            float yTranslation = (this.Height - originalHeight * scale) / 2.0f;

            Matrix transformation = new Matrix();
            transformation.PostTranslate(xTranslation, yTranslation);
            transformation.PreScale(scale, scale);

            Paint paint = new Paint();
            paint.FilterBitmap = true;

            canvas.DrawBitmap(originalImage, transformation, paint);

            return resizedBitmap;
        }
    }
}

 

The Android ScrollView which is associated with the Xamarin Forms ScrollView has the following native properties:

  • VerticalScrollBarEnabled: Make the vertical scrollbar visible or hidden
  • HorizontalScrollBarEnabled: Make the horizontal scrollbar visible or hidden
  • OverScrollMode: Always enable the native bounce effect on Android ScrollView
  • Background: Allows to set the background drawable for the ScrollView

As you may have noticed we are converting our Xamarin Forms Image Source BackgroundImage to a Bitmap image using our extension.

Then we are resizing out Bitmap image according to the Width and Height of the ScrollView to fit to the full background to be wrapped around a BitmapDrawable and set to the Background of ScrollView.

There you go! 😀

Let’s use it… 😉

Alright now that’s done, let’s consume this in our PCL project.

<StackLayout Padding="10,0,10,0">

	<Label Text="Welcome to Xamarin Forms!"
		   VerticalOptions="Center"
		   HorizontalOptions="Center" />

	<local:BloopyScrollView 
	IsNativeBouncyEffectEnabled="True"
	IsVerticalScrollbarEnabled="False"
	IsHorizontalScrollbarEnabled="False">
	<local:BloopyScrollView.BackgroundImage>
	  <FileImageSource File="xamarinBackgroundImage.png"/>
	</local:BloopyScrollView.BackgroundImage>
	
			<Label
			  FontSize="22"
			  HeightRequest="400"
			  Text=
			  "Whatever your text content to be displayed." />
			  
	</local:BloopyScrollView>

</StackLayout>

 

As you can see I have inserted my BloopyScrollView in a StackLayout and as the content of the ScrollView I have added Label. Well you can add any content you want or set any Height or Width as you wish.

Notice that I have set IsNativeBouncyEffectEnabled to be True as I want to see the native Bouncy effect. Then I have disabled the Vertical and Horizontal Scrollbars from the properties we added earlier. Then finally I have added the BackgroundImage and set the FileImageSource to the ImageSource type, where as I have placed the image in the native Resource folder, as you would do with any defualt Xamarin Forms Image. 😉

Now let’s see the results… 😀

bloopscrollview-on-ios-lowq  bloopscrollview-on-android-lowq

Yaay! 😀

As we expected the Vertical and Horizontal Scrollbars are disabled and our ScrollView has full native bouncy effect accordingly.

Also you can see the Background Image nicely resized itself and fit to the background of the BloopyScrollView. 😀

Happy dance! lol

Recap Stuff…

Now there’s some stuff I wanted to recap, that is you may have noticed that when I was resizing the Image, I needed the Control’s Height and Width, and where I have acquired those properties are in two different places on each Android and iOS renderers.

To be specific I have accessed the Control’s Width and Height on Android right from the OnElementChanged method, but on iOS renderer I have accessed those values from the  OnPropertyChanged method’s Height property event. 

This is because of the differences of the Rendering cycling of Android and iOS, whereas on Android right at the firing of the Custom Renderer it assigns itself Width and Height. But on iOS we have to access them indirectly by waiting till those properties are set, by listening to the OnPropertyChanged event.

Get it on Github! 😀 XFImprovedScrollView

Cheers everyone!

Pass this on to another developer to make them smile! 😀
– Udara Alwis

An awesome Image Helper to convert Xamarin Forms ImageSource to iOS UIImage or Android Bitmap…

The default Xamarin Forms ImageSource is good, but it doesn’t provide all the properties of an Image, not as much as native Image types of Android or iOS. This is why sometimes we need to drill down to the native level of Image handling sometimes, specially when you’re dealing with Custom Renderers, or complex Image manipulation stuff in Xamarin.

So yeah it’s no surprise you will run into the need of converting the default Xamarin Forms ImageSource to native Image type in iOS and Android, respectively UIImage or Bitmap types.

Well I know I did. lol 😛

How ? 😮

So how could you do this ? Well, something intermediate for both Xamarin Forms ImageSource and the native Image types is the byte[] array. 🙂 But I’m gonna take a pass on it, since it’s too much of trouble and process, which could lead to bad memory consumption. 😦 Instead, why don’t we deal with this straight away. 😀

This is how I did it.. 😉

Now when it comes to Xamarin Forms almost everything is handled by drilling down to the native levels of the platform. Likewise ImageSource  during the runtime is handled through three types of Native Handlers that are as follows,

  • ImageLoaderSourceHandler
  • FileImageSourceHandler
  • StreamImagesourceHandler

Now for each Native environment, these handlers implements a LoadImageAsync() method, which loads the type of Native Type image for a given ImageSource.

This is usually done under the hood, but we need to access this same functionality on the go for our own requirements, so let’s do it by our own implementation.

Let’s create our Android Image Helper…

So we are going to create a Public class with static methods that could be used as extension methods in our Native Project levels. So go ahead and create the AndroidImageHelper class in your Xamarin.Android project level.

sameple

 

public class AndroidImageHelper
{
	private static IImageSourceHandler GetHandler(ImageSource source)
	{
		IImageSourceHandler returnValue = null;
		if (source is UriImageSource)
		{
			returnValue = new ImageLoaderSourceHandler();
		}
		else if (source is FileImageSource)
		{
			returnValue = new FileImageSourceHandler();
		}
		else if (source is StreamImageSource)
		{
			returnValue = new StreamImagesourceHandler();
		}
		return returnValue;
	}

	/// <summary>
	/// For converting Xamarin Forms ImageSource object to Native Image type
	/// </summary>
	/// <param name="source"></param>
	/// <param name="context"></param>
	/// <returns></returns>
	public static async Task<Bitmap> GetBitmapFromImageSourceAsync(ImageSource source, Context context)
	{
		var handler = GetHandler(source);
		var returnValue = (Bitmap)null;

		returnValue = await handler.LoadImageAsync(source, context);

		return returnValue;
	}
}

 

Alright there we go, as you would have expected we are using the native level Handlers of the ImageSource and retrieving the native image type as I explained earlier through the LoadImageAsync() method. Of course you need to pass a reference of your current Context since Android requires the context reference to almost every execution related to the UI stuff.

First we are getting the GetHandler type by the ImageSource, then we are calling the method above to retrieve the Bitmap image and returns back to the caller.

Let’s create our iOS Image Helper…

So just like on Android let’s do the same on iOS and create the public class IosImageHelper in your Xamarin Forms iOS project level.

sameple

public class IosImageHelper
{
	private static IImageSourceHandler GetHandler(ImageSource source)
	{
		IImageSourceHandler returnValue = null;
		if (source is UriImageSource)
		{
			returnValue = new ImageLoaderSourceHandler();
		}
		else if (source is FileImageSource)
		{
			returnValue = new FileImageSourceHandler();
		}
		else if (source is StreamImageSource)
		{
			returnValue = new StreamImagesourceHandler();
		}
		return returnValue;
	}

	/// <summary>
	/// For converting Xamarin Forms ImageSource object to Native Image type
	/// </summary>
	/// <param name="source"></param>
	/// <returns></returns>
	public static async Task<UIImage> GetUIImageFromImageSourceAsync(ImageSource source)
	{
		var handler = GetHandler(source);
		var returnValue = (UIImage)null;

		returnValue = await handler.LoadImageAsync(source);

		return returnValue;
	}

}

 

So here also we are using the same implementation as we used on Android, instead the LoadImageAsync() returns an UIImage.

Now let’s use it… 😉

Alright let’s see how to use these extensions in our code. 🙂

// Useage in iOS

UIImage _uiImageconverted = await IosImageHelper.GetUIImageFromImageSourceAsync(yourImageSourceObject);

// Useage in Android

Bitmap _bitmapImageconverted = await AndroidImageHelper.GetBitmapFromImageSourceAsync(yourImageSourceObject, this.Context);

 

There you have it, now you have your Xamarin Forms ImageSource converted to the given Native Image type, either iOS UIImage or Android Bitmap Image type. 😀

Enjoy! 😀

Cheers everyone!

How to deal with Implementing an iOS optimized UI design on Android with Xamarin Forms?

When it comes to Cross-Platform mobile development, it is very crucial to have Screen Design concepts that are compatible for all the targeting platforms (Android/iOS/WinPhone), or at least to have separate Screen Designs for targeting platforms, when you’re using a platform such as Xamarin Forms (allowing you to develop apps with Native Look and Feels).

but…

What if you are out of luck in such requirements? What if as the developer you’re only given the Design Screens that only optimizes for one specific mobile platform?

and worst…

You’re expected implement the same design for both Android and iOS regardless of the design’s optimization?

my story…

Let me put it this way,

the project I’m currently working is a Cross-Platform Mobile Application building on top of Xamarin Forms. I am given a bunch of Design Screens that are optimized for iOS UI patterns, and my seniors wants me to implement the same UI Design for Android as well, regardless of the Android UI patterns.

So despite Xamarin Forms gives Native Look and Feels I am asked to implement the same design that are optimized for iOS into Android regardless of Android UX patterns.

Oh well.. look at that, so mostly to go against the Android UI Design best practices, just implement the iOS optimized design straightaway. (Well my UX Lead seems to be an iOS geek) 😛

Well this would have been better if we were developing on a Hybrid framework which uses HTML5 so that we could simply throw the same rendered result for both Android and iOS, but since its Xamarin Forms, which allows you to use Native Looks and Feels after compilation, it’s going to be a mess!

…gotta suck it up!

As the developer, I have no choice but to get this done somehow, even though the hell breaks loose! because it’s my JOB! 😛

Well for the User’s perspective, getting rid of the Android looks and feel, will surely disturb the User Experience on Android.

Challenges..

So as the developer, here are some challenges I faced…

Difference between iOS Designs VS Android Designs!

evasion-ios-71

When you take a iOS Mobile App design, its mostly a static UI design, which uses mostly pixel perfect and screen coordination perfect values for placing the components on the Screen. This is because for iOS devices almost all their devices uses a pre-defined common Screen-Size-Resolution or as in Screen Height-Width Ratio.

top-android-phones1

but when it comes to Android devices, there’s a massive sea of fragmented Screen Sizes, and according to researches it only keeps on growing, therefor for Android Mobile App Designs are compiled with non-static flexible UI Design, which has room to stretch and shrink accordingly as much as possible without disrupting the User Experience.

Dealing with the Android sea of Device…

Just to give you a head start take a look at the following illustration which shows the different Android screen sizes that are available in the market by 2016! :O

screen-shot-2014-08-21-at-1-49-11-pm-1280x748

So you have to deal with the completely unexpected screen-sizes and resolutions, when you try to implement an iOS optimized UI Design for Android. Because of the pure difference I mentioned earlier, how could you take a static pixel-perfect, component coordinates fixed design and adopt it and make it flexible for the massive sea of device fragmentation of Android? 😦

…but not giving up!

So as the job role of a Developer we are suppose to solve problems and accept whatever the challenge throws at us, even the hell breaks loose!

So this is how I resolved it with Xamarin Forms!

So how did I do it?

So let’s go through one by one!

1. RelativeLayout for ze rescue…

Yes that’s right, Xamarin Forms provides several types of Layout types for the ease of Developer and luckily they also provide a Layout called Relative Layout. And yes it does exactly from what it’s name shows.

layouts1

RelativeLayout is used to position and size views relative to properties of the layout or sibling views.

Unlike StackLayout and GridLayouts which most developers use in Xamarin Forms, for the ease of use, RelativeLayout allows you to place its Children Relatively to each other or for the parent view.

Therefore when dealing with different screen sizes of Android we could push the UI to render itself Relatively to given parameters while maintaining the expected UI design as much as possible.

Take a look at the below example from Xamarin docs:

flag1

As you can see, using this Layout we could implement and render the same Design across all mobile platforms. Hence we are placing all the components on the screen, RELATIVE to each other.

2. Always use Constraint type as RelativetoParent!

RelativeLayout provdes three types of Constraint type to place your Components inside the layout, that are

  • RelativeToParent: Set the value relatively to the ParentView
  • RelativeToView: Set the value relatively to another View in the same parent Layout
  • Constant: Set the value as a Constant value

So out of these three types, I would recommend always sticking to the RelativeToParent type, which allows you to have more compatibility towards Android screen sizes, because we are relying on the Parent View which takes up the whole screen Heigh/Width/X or Y properties. So its always better to take relative values accordingly to the Parent instead of another View in the same Parent Layout, which may or may not be behaving as we expect, but as of Parent view, we are sure of its layout.

3. Use XConstraints and YConstraints

Now you must remember how I was crying out loud about having to implement a pixel-perfect screen coordinates fixed design on Android. 😛

So we are going to implement the exact same concept but RELATIVELY!

So with RelativeLayout we can set the X Y locations of a component Relatively to the parent or another view, which helps you place the component on the screen without any worries since those values will get set relatively at the run time. Yep no more worries about those coordinates for Android! 😉

4. Do not use StackLayout or GridLayout inside RelativeLayout!

That’s correct do not use them inside the RelativeLayout and place your child components inside them. Which will lead to the same issue we tried to solve at he beginning, because those Child elements will adopt themselves accordingly to the Stack or Grid Layouts, not for the RelativeLayout. So if you can try to place your child components inside RelativeLayout directly by setting the X/Y/Width/ and Height constraints.

5. Avoid Constants and use Factor…

Yes, with Factor you can get the best suited value according to the ratio of the Relative property, whether its X, Y, Width or even Height! 🙂

And please, stop using Constants, unless you really wants to, because then you will be completely killing the purpose of using the RelativeLayout, hence we need to achieve fluid flexibility to render the iOS optimized design on Android with Xamarin Forms! 😉

6. Also you could use Absolute Layout!

This also does something similar but a little bit differently which could also be used in our situation.

AbsoluteLayout positions and sizes child elements proportional to its own size and position or by absolute values.

So there’s something to keep in mind as well. 😉

Something to keep in mind…

Usage of RelativeLayout is going to be very costly during the run time, takes a lot of processing power to render the UI due to its Relative behaviour of the measurements, meanwhile Jason Smith also recommends avoid using RelativeLayout and instead stick to StackLayouts and GridLayouts.

But unfortunately in order to deal with this kind of scenarios, you have to compromise something , not to mention disrupting the native User Experience of the app.

Conclusion

So that’s how deal with my situation when I was given a iOS Optimized mobile design to be implemented on Android with Xamarin Forms! 😀

Very well then, if anyone else has gotten into this situation, I hope this post has helped you in some way! 🙂

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!