Tag Archives: Xamarin Android

So I played around with Android Emulators in Visual Studio 2019!

Let me share some of my experience with playing around with the latest updated Android Emulators in Visual Studio 2019!

Microsoft had finally rolled out a full fledged Android Emulator set up (Xamarin Android Device Manager) that’s very stable and much easier to use with Xamarin mobile development, expiring the previously buggy always-out-dated VS Emulator set up that was shipped for Xamarin dev. Yeah seriously I hated that and had a lot of issues using those emulators.

Backstory…

So recently I got a little deep into the new Xamarin Android Emulator set up in Visual Studio 2019, where I had to build a whole bunch of custom Emulators for some experiments. I had to do a lot of fine tuning and customization for those Android Virtual Devices. Also I had to focus on Performance management as well, which was quite interesting to deal with given the HAXM and Windows Hyper-V separation.

It was a great learning experience, where I noticed a lot of new features and differences between the previous VS Emulator set up compared to this one.

So here I am sharing my experience…

Getting Started…

Here are some important articles that might be important for anyone to get started…

Managing Virtual Devices with the Android Device Manager
https://docs.microsoft.com/en-us/xamarin/android/get-started/installation/android-emulator/device-manager?tabs=windows&pivots=windows
Great step by step guide on how to update Device Manager, create new Virtual Devices, Customizing and Managing the performance further…

Editing Android Virtual Device Properties
https://docs.microsoft.com/en-us/xamarin/android/get-started/installation/android-emulator/device-properties?pivots=windows
Step by step guide for Editing Virtual Device Properties…

Troubleshooting
https://docs.microsoft.com/en-us/xamarin/android/get-started/installation/android-emulator/troubleshooting?pivots=windows
Basically this includes fixing HAXM issues, Hyper-V issues not configured up in BIOS, or not Enabled in Windows, etc.. It’s quite easy to miss those configurations so you might want to focus twice on those if you ever run into any issues.

The official documentation from Microsoft does a great job of explaining how to get started and all, so I won’t be repeating the same on my blog post, rather I would focus on the important bits that I experienced and issues I ran into which I eventually solved during my playing around! 😉

The adb binary is obsolete!?!

So this is the first weird issue I ran into when I tried out the Android Emulator on Visual Studio 2019, there is a reason why I call it weird though… lol

“The ADB binary found at C:\Program Files (x86)\Android\android-sdk\platform-tools\adb.exe is obsolete and has seriousperformance problems with the Android Emulator. Please update to a newer version to get significantly faster app/file transfer.”

Yeah notice the “seriousperformance” lol, no idea why they haven’t spell-checked the error message. Anyhow I kept on getting this warning message every time I launched my Android Emulators, I couldn’t really understand why, since I had VS 2019 updated to the latest version at the time. But later only I figured out that you need to manually update some other bits from your Android SDK Manager as shown in below steps…

Update Android Emulator!

You need to make sure to update your Android Emulator version, from the Android SDK Manager as shown below…

Go to the Tools tab, and expand the Android Emulator section, make sure you have installed the latest version as shown there. Most likely this won’t be updated by the usual VS Updater process, which was the issue in my case.

Also one more thing you need to do, since the “obsolete ADB binary issue” could be occurred from either one of these.

Update Android SDK Build Tools!

Go to Tool tab and expand Android SDK Build Tools section…

You need to make sure to have the latest version installed, and remove any older versions already installed of the Android SDK Build Tools as shown above. Because this could be causing the “obsolete ADB binary issue” that I mentioned earlier.

Intel HAXM vs Windows Hyper-V!

Now some devs seem to be getting confused about this, first think of it as this, you have an Android Emulator and you have these two different support systems that you can use to accelerate the performance of it. You can use only one of them, its either Intel HAXM or Windows Hyper-V, you cannot use both at the same time. Got it? 😉

Check out the docs: Hardware acceleration for emulator performance (Hyper-V & HAXM)
Well the documentation from Microsoft does a great job at explaining both these setups in great detail step by step.

I personally tried both of them separately in my Lenovo Windows Laptop, that’s running on Intel Core i7 Processor. Keep in mind, if you want to try Intel HAXM then you need to disable Windows Hyper-V and vise-versa, otherwise you’ll run into all kinds of issues.

Aha! Intel HAXM!

Intel’s Hardware Accelerated Execution Manager (HAXM). HAXM is a virtualization engine for computers running Intel CPUs. – Source

Check if your Intel Processor supports Virtualization Technology: https://www.intel.com/content/www/us/en/support/articles/000005486/processors.html

You development machine needs to be running on an Intel processor in order for HAXM to work, even in that case that processor needs to support Intel VT, you can check it from the link I shared above. This works on both Microsoft Windows and Apple Mac OS systems, as long as the hardware requirements are met.

Intel HAXM has always been there since long time back for accelerating the performances of Android Emulators, so it supports Emulators that are running older versions of x86-based virtual devices.

If you’ve successfully set up Intel HAXM, you can check status of HAXM set up as follows:

sc query intelhaxm

Microsoft recommends this option to be your default choice for setting up your Android Emulators. But if your dev set up doesn’t support Intel HAXM acceleration, next let’s see the second option…

Ooo! Windows Hyper-V!

Microsoft’s Hyper-V and the Windows Hypervisor Platform (WHPX)Hyper-V is a virtualization feature of Windows that makes it possible to run virtualized computer systems on a physical host computer. Source

As obvious as it is, this only works on Windows OS! This was introduced for Android Emulators quite recently, so you need to have the following set up for your local Android SDK and Tools:

  • Android Emulator package 27.2.7 or later
  • Android SDK Tools version is 26.1.1 or later

Also you need to have Microsoft Windows 10 Pro, Enterprise, or Education version installed. You can check if your system could support Windows Hyper-V as follows:

systeminfo

If all those values are shown as Yes, then you can go ahead and enable Windows Hyper-V on your machine 🙂

So, Intel HAXM or Windows Hyper-V!?!

Yeah, so which is better? given that you can ONLY think of if you’re development PC is compatible for both of them!

I’ve tried both of them, and to be honest I’ve seen much better performance with Intel HAXM Acceleration in my Windows 10 Lenovo Laptop, with Intel Core i7 processor. Since Microsoft docs also recommend this option, yes I would definitely recommend this be your primary choice as well for better performance.

FastBoot, Intel HAXM only!

Now this is something strange that I noticed during my try outs, FastBoot feature does not seem to be supported on Windows Hyper-V, during every launch it was executing a fresh cold boot. But with Intel-HAXM it works like a charm! So that’s probably something you need to keep in mind! 😉

If you’re not familiar with FastBoot, let me walk you through a little intro…

FastBoot vs ColdBoot!

You can see this configuration in the Properties from the Android Device Manager as following…

FastBoot allows you to directly boot your Android Emulator from a pre-saved snapshot state image, so you get a super fast boot and be able to deploy the apps faster when you launch directly from Visual Studio. Every time you close the Emulator it will save a snapshot of it’s current state, which will be used in the next boot.

So what is ColdBoot?

The opposite of FastBoot is ColdBoot, where during every launch the Android Emulator executes a fresh boot instance. ColdBoot is by default disabled as you can see in my previous screenshot, you need to tick on the fastboot.forceColdBoot in order to enable this. You should only use this if you need a fresh boot in each time your Emulator launches.

Now as obvious as it is, keep in mind you can’t use both of them at the same time, so make sure to tick on either forceColdBoot or forceFastBook as you prefer. 🙂

Maximum performance!

For maximizing the performance of your Android Virtual Device, I found utilizing on these three properties quite useful,

  • hw.gpu.mode – the GPU allocation set up of your Emulator
  • hw.cpu.ncore – number of Processor Cores allocated to your Emulator
  • hw.ramsize – amount of RAM size allocated to your Emulator

Now the higher values you set for those properties will definitely provide better performance in your Android Emulator, but it will require consumption of more resources from your development machine, so make sure to cross check against it when you tweak those up!

hw.gpu.mode -> host!

By default this property will be set to “auto” mode which will set the Emulator to decide whether to use device GPU processor to render the Emulator’s GPU processing or use Software GPU Emulation.

If you’ve got a dedicated powerful GPU in your development machine, I would say this should set the “host” option for the GPU emulation in the Emulator, which forces the Emulator to use the system GPU device, which in return provides great performance.

New Camera magic!

Since the latest update Android Emulators are now updated with an awesome Camera emulation feature which allows you to emulate a virtual 3D scene. You can enable this by setting the hw.camera.back property to virtualscene value.

This is such an awesome feature it allows you to navigate through an emulated virtual scene in a 3D space, with full 360 degree camera angle movements.

Now that’s some awesomeness eh! 😉

LCD Density!

You can set the density of the screen in your Android Emulator, to a list of custom values possible to set up the density-independent pixels for rendering.

Keeping in mind, setting hw.lcd.density to 160 value will cause the emulator to render each pixel in the device screen equivalent to your host machine’s physical screen pixels. You should be able to find the most suited screen density for the screen resolution you have set up for your emulator.

Here’s an example of screen resolution 1080×2160 with each lcd screen density option available from 160, 240, 213, 320, 420, 480, to 560 as follows…

Well well you can see how it clearly changes the UI rendered DPI based on the density settings you have set up… 😀

Custom Resolutions play!

So one tricky thing I got to play around was creating Android Emulators with custom screen resolutions, now this really requires a careful set up of the screen Density settings as well.

So for the fun of let me show you a custom Android Emulator that I build with the screen resolution equivalent to iPhone 11 which has height to width 1792×828 resolution…

So something to keep in mind is that, right on the first try you wouldn’t get screen density property compatible for the custom screen resolution, so you will need a few try outs to sort out the density property. Yes it took a few try outs for me as well! 😉

hw.lcd.height – screen height, hw.lcd.width – screen width, hw.lcd.density – screen density

Setting up skin.path value…

When you set up a custom resolution to your Emulator, you need to make sure to update the skin.path property value as well.

Set this value followed by the format resolution, widthxheight as shown here.

Not sure how this related to the custom resolutions, but if you miss this step your emulator screen will end up with the default resolution value set up here upon create. So make sure to set this value according to your custom screen resolution as well 🙂

Enabling on-screen Keys…

[ back | home | recent ] yes those on screen keys might not be available when you first create your custom emulator, to enable this you need to disable the hw.mainKeys property.

You should un-tick this property value to enable on-screen navigation keys.

And the resulting should be as straight as below… 😉

Well there you have it, working like a charm! and that’s pretty much it for all the tricks and lessons that I learned during my playing around with Android Emulators in Visual Studio 2019!

Conclusion

The latest updates to Android Device Manager allows you to create Android Virtual devices or emulators with incredible flexibility and easy to manage interface, with improved performances and enhancements unlike before. 🙂

The Microsoft documentations provide an incredible support for getting started step by step, and even customizing your Android emulators for Xamarin Development with ease.

I happened to be stumbled upon a great opportunity to learn a few tricks and lessons for complex use of the latest Android Virtual Devices for Xamarin Development, which I had shared in this article. 😉

Hope it helps any of you fellow devs out there!

Share the love! Cheers! 😀

Using SMS Retriever API in Xamarin Android!

Let’s use the SMS Retriever API in Xamarin Android, and possibly avoid the troubles of new Google Play Store SMS/Call Log access restrictions! 😉 Is your Android App ready for the new Google Play Store permission policy?

SMS Retriever API, in a nutshell…

Android SMS Retriever API allows you to access the SMS Messages in the phone without having to request SMS read access permission, thus giving a complete peace of mind for the user. 🙂 Allowing specific SMS messages to be read from the Inbox, which are specifically targeted to be delivered for the  app we’re requesting from. This is the perfect solution for One Time Password (OTP) mobile number verification implementation in our Android apps.

Furthermore from Google Docs: https://developers.google.com/identity/sms-retriever/

Now that the introduction is out of the way… Let’s get started!

How it works, in short…

NO! I’m not gonna get into detailed explanation, but in simplest terms we are going to have an object called SmsRetrieverClient that’s going to wait for an incoming SMS message with the matching hash key to the app we are using. This active waiting is going to execute for 5 minutes and automatically dispose itself.

When the certain SMS arrived at the inbox during the 5 minute waiting , the SmsRetrieverClient then sends a broadcast to the app with the captured message content, for any listening broadcast receivers registered in the app.  From there we pick up the message inside our broadcast receiver and we process it or do whatever the heck we want with it. 😛

But in case if the SMS wasn’t received by the phone it would still execute the broadcast but with a time out failure code, so that we know the 5 minutes waiting exceeded and the SMS wasn’t received or read.

So there’s mainly 2 components to it, SmsRetrieverClient object, and the Broadcast Receiver object. Not to mention the App Hash key, which is also very crucial element here, you need to make sure the SMS that’s sent to the device has the App hash key that’s derived from the signing keystore of the app’s running instance.

In Xamarin…

Yes this is completely available in Xamarin Android as well, right out of the box! Just a matter of figuring out the right namespaces and method calls comparing to the official Google Android Docs! 🙂

Although I’m quite surprised I could not find any official Documentation from Xamarin regarding this important API. Thus here I am filling that void! 😀

Let’s get started!

Add em Nuget!

To use SMS Retriever API in Xamarin we need to install Xamarin.GooglePlayServices.Auth nuget package to our Android project.

Just pick the latest version as you prefer and hit install.

Activate the SMSRetrieverClient…

Then we need to implement the executing of the activation of SMSRetrieverClient that is the client object that’s going to actively watch out for any incoming SMS messages with the hash key that is similar to the app we are requesting it from.

You could initiate the SMSRetrieverClient inside a button click event or invoke it from a Service instance method, choice is up to you. 🙂

private void btnStartSMSRetreiver_OnClick(object sender, EventArgs eventArgs)
{
	// Get an instance of SmsRetrieverClient, used to start listening for a matching SMS message.
	SmsRetrieverClient _client = SmsRetriever.GetClient(this.ApplicationContext);
	// Starts SmsRetriever, which waits for ONE matching SMS message until timeout
	// (5 minutes). The matching SMS message will be sent via a Broadcast Intent with
	// action SmsRetriever#SMS_RETRIEVED_ACTION.
	_client.StartSmsRetriever();
}

As you can see we’re instantiating the SmsRetrieverClient using the Application Context, and calling the StartSmsRetriever() method to activate listening to the incoming SMS messages with matching app hash key included.

A little cherry on top…

Here are some extra bits you could adopt if needed regarding the SmsRetrieverClient. You could get the return result of the SmsRetrieverClient initiation as follows…

...

	var task = _client.StartSmsRetriever();

	// You could also Listen for success/failure of StartSmsRetriever initiation
	task.AddOnSuccessListener(new SuccessListener());
	task.AddOnFailureListener(new FailureListener());
}

...

internal class SuccessListener : Java.Lang.Object, IOnSuccessListener
{
	public void OnSuccess(Object result)
	{
		// do as you wish on Success init
	}
}

internal class FailureListener : Java.Lang.Throwable, IOnFailureListener
{
	public void OnFailure(Exception e)
	{
		// do as you wish on Failure init
	}
}

And even await for the init result asynchronously as follows…

...
var task = await _client.StartSmsRetriever();
...

But don’t forget to switch the caller method to an async method! 😉

Well that’s just some cherry on top features if you ever wanted to try!

Next the BroadcastReceiver…

So here’s the other piece of the puzzle, the BroadcastReceiver that will be listening to the broadcasts of the above SmsRetreieverClient.

SMS Retriever API has provided us with an intent filter SmsRetriever.SmsRetrievedAction which we will use to register our BroadcastReceiver, which we’re going name as SMSBroadcastReceiver, and implement as following…

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { SmsRetriever.SmsRetrievedAction })]
public class SMSBroadcastReceiver : BroadcastReceiver
{
	public override void OnReceive(Context context, Intent intent)
	{
		if (intent.Action != SmsRetriever.SmsRetrievedAction)
			return;

		var extrasBundleundle = intent.Extras;
		if (extrasBundleundle == null) return;
		var status = (Statuses)extrasBundleundle.Get(SmsRetriever.ExtraStatus);
		switch (status.StatusCode)
		{
			case CommonStatusCodes.Success:
				// Get SMS message contents
				var messageContent = (string)extrasBundleundle.Get(SmsRetriever.ExtraSmsMessage);
				// Extract one-time code from the message and complete verification
				// by sending the code back to your server.
				ShowResultOnUI("SMS retrieved: " + messageContent);
				break;

			case CommonStatusCodes.Timeout:
				// Waiting for SMS timed out (5 minutes)
				// Handle the error ...
				ShowResultOnUI("Timed Out Error! SMS retrieval failed!");
				break;
		}
	}
}

So once the SmsRetrieverClient does its job, either success or failure it will hit our Broadcast Receiver above and pass in the results, with Status code and Content of the Message if success, which will be included in the Extra Bundle as you can see above.

Once we receive the results, its up to you to do whatever you want with it, as you can see in the code itself! 😉

That’s pretty much it! simple and straightforward eh! 😀 But I wouldn’t end there without mentioning some important other bits that you need to make sure to get it right!

Other important bits…

Here are some helpful tips for you to troubleshoot any issues you’re having with getting the SMS Retriever API to function as it should.

SMS format..

You need to make sure you’re sending the correct SMS format as mentioned in the Google Android Documentation.

<#> Your ExampleApp code is: 123ABC78
FA+9qCX9VSu

It should be same format as above, although you could make some alterations to the message content, but the structure should be same. Start with “<#>” followed by the content of the SMS and ending with the App Hash key. You can learn more about it from their documentation: SMS Retriever API: Construct a verification message

Please, get your App Hash Key right!

I’ve seen people get this wrong all the time. It is such an easy simple process but a delicate one. So if you can’t get your implementation of SMS Retriever API to function properly, you should definitely take a look at your app hash key, whether you’ve generated the correct key and using the properly in the SMS content.

Given Xamarin Android development, there’s no official documentation provided by Xamarin yet, that’s why I have written a step by step blog article to how to easily generate the accurate App hash key, give it a try if it could be of any help…

You can check it out here: App Hash Key Helper extension for Xamarin Android apps!

Let’s see it in action! 😀

Let’s fire it up and see the beauty of Android SMS Retriever API in Xamarin!

Look at the beauty eh! 😀 No SMS Read permission required 😉 way to give some peace of mind for your users for a simple functionalities such as OTP or Phone number verification!

You can try out my full blown demo in my github repo:

https://github.com/UdaraAlwis/XAndroidSMSRetrieverAPIDemo

It’s got all the bits I talked about above fully functional 🙂

in Xamarin.Forms Android?

Even if you’re using Xamarin.Forms the same implementation above can be applied easily. Just simply create a platform specific service to invoke the SMSRetrieverAPIClient on Android and call it from Xamarin.Forms at run time, then from the BroadcastReceiver just return back the results by using Xamarin.Forms MessagingCenter… 😉

Simple eh! 😀

There you have it fellas!

Cheers! Share the love! 😀 ❤

App Hash Key Helper extension for Xamarin Android apps!

Remember my last post “Generating App Hash key for SMS Retriever API for (Xamarin incl.)…” where I shared with you guys how to successfully  generating the App hash key in both MacOs and Windows environments without any hassle?

Now this is the improved alternative of it! making the whole process much easier specially for Xamarin Android development!

Previously…

So earlier we looked at how we could generate the App Hash key straight away from MacOS Terminal or on Windows with the keystore hex generation followed by the Xamarin Android helper method execution to retrieve the app hash key!

That specific helper method I had extracted partially from the Google’s official documentation sample regarding the SMS Retriever API, which I couldn’t completely port to Xamarin Android at that time while I was working on my private project.

But later I took a proper look at it and figured out how to completely port it to Xamarin Android, with a few minutes of back and forth between the Java code and C# Xamarin namespaces! 😀

Easier and Faster method!

Now with the fully ported code, as an extension helper class, we could easily generate the Hash key for our Xamarin Android app either on Windows or Mac using Visual Studio, without having to use any external Terminal or Command prompt.

but you need to follow some pre-requisites to get it to properly work..

Let’s get started!

Get your pre-requisites right!

You need to make sure you’re using the correct Keystore file to sign your APK during build, therefore navigate to your Xamarin Android project properties and set the correct Keystore file path and configuration.

In Visual Studio on Windows:

In Visual Studio on Mac:

That’s done!

Finally make sure you have given the proper app package name or app id to your app in the same project properties. ex: com.testapp.xyz

Why you ask? Since we’re directly generating the app hash code from the project itself, we need to make sure during the compilation the app, the final APK is signed using the keystore we are hoping to use in production. So we can retrieved the signed hash hex from the app Context at run time and the app id to generate the app hash code. 🙂

Then let’s begin the AppHashKeyHelper implementation… 😉

Let the implementation begin…

Let the implementation begin! lol 😀 So here is the complete ported helper class for generating the app hash key for your Xamarin Android app!

Simply copy the whole code to anywhere in your Xamarin Android project, and you could straight away call it from anywhere in the app to generate the app hash key!


using System;
using System.Linq;
using System.Text;
using Android.Content;
using Android.Content.PM;
using Android.Util;
using Java.Security;
using Java.Util;
namespace WhateverNameSpace.Droid.Util
{
/// <summary>
/// This is a helper class to generate your message hash to be included in your SMS message.
///
/// Without the correct hash, your app won't recieve the message callback. This only needs to be
/// generated once per app and stored.Then you can remove this helper class from your code.
///
/// Ported to Xamarin C# from the AppSignatureHelper.java offcial Android sample
/// – Udara Alwis
/// </summary>
public class AppHashKeyHelper
{
private static string HASH_TYPE = "SHA-256";
private static int NUM_HASHED_BYTES = 9;
private static int NUM_BASE64_CHAR = 11;
/// <summary>
/// Retrieve the app signed package signature
/// known as signed keystore file hex string
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private static string GetPackageSignature(Context context)
{
PackageManager packageManager = context.PackageManager;
var signatures = packageManager.GetPackageInfo(context.PackageName, PackageInfoFlags.Signatures).Signatures;
return signatures.First().ToCharsString();
}
/// <summary>
/// Gets the app hash key.
/// </summary>
/// <returns>The app hash key.</returns>
/// <param name="context">Android app Context.</param>
public static string GetAppHashKey(Context context)
{
string keystoreHexSignature = GetPackageSignature(context);
String appInfo = context.PackageName + " " + keystoreHexSignature;
try
{
MessageDigest messageDigest = MessageDigest.GetInstance(HASH_TYPE);
messageDigest.Update(Encoding.UTF8.GetBytes(appInfo));
byte[] hashSignature = messageDigest.Digest();
hashSignature = Arrays.CopyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
String base64Hash = Android.Util.Base64.EncodeToString(hashSignature, Base64Flags.NoPadding | Base64Flags.NoWrap);
base64Hash = base64Hash.Substring(0, NUM_BASE64_CHAR);
return base64Hash;
}
catch (NoSuchAlgorithmException e)
{
return null;
}
}
}
}

We’re simply passing in the Android App Context, which will then first retrieve the signed kestore hash string from the Package Manager.

Then we retrieve the app package name from the Context itself, and move ahead with the usual encrypted key generation.

I would recommend calling this from your MainActivity itself, since this is just a one time execution in your local debug environment.

There you go! Simple as that! 😀

Now once again, keeping in mind to make sure to remove the above helper class call from your project code, before you submit your final APK to the Play Store, since google does not recommend generating the App’s hash key during user run time. Just simply retrive your hash key and remove the code, and then set it up in your SMS API gateway execution.

Thats it! 😀

Cheers!

Share the love! 😀 ❤

Generating App Hash key for SMS Retriever API for (Xamarin incl.)…

Trying to generate your app’s Hash Key for the implementation of new Android SMS Retriever API? Still couldn’t get it to work? Well the problem could be in the actual generation process of the has string!

And here are some ways you could actually make sure to generate the valid hash string to get the functionality working.

Specially if you’re developing on Windows, or better working on a Xamarin Android app? I’ve got some goodies to make it work as well! 😉

App Hash string for SMS Retriever API

Anyhow, to use the SMS Retriever API we need generate our App’s unique Hash string which is a combination of app’s package name and your app’s public key certificate. Once the SMS is received into the Inbox the SMS Retriever API looks for any matching hash key in the message corresponding to the app that requested to read the SMS, if it finds a perfect match it will kick in the execution of retrieving the SMS string, otherwise it will time out. So without the accurate app hash key the SMS Retriever API will not kick in at all. That is why it is very crucial we generate the correct app hash key for our app using the App package name and keystore hash.

Troublesome!

Although according to the official Google Documentation, it should be easy and straight forward, but it is not, specially if you’re using a Windows Dev Environment, which could be troublesome at times. To add some topping on to that, if you’re working on a Xamarin Android project in Windows, you’re in deep troublesome waters, since even Google Docs only provides samples for the Android Java implementation.

Then the sample command that Google Docs provide doesn’t really throw any error if anything goes wrong during, wrong parameter, or a wrong keyword, during hash string generation, it simply returns a false hash string, which makes things worse!

This is actually something I experienced while I was developing one of our Xamarin Android applications. Oh yes! that’s even more annoying since there’s no official documentation or Xamarin sample of the implementation code regarding that API. 😦

Hence Google’s doc command failed me I had to play around with the parameters we’re passing in to the command, re-arrange and modify to get it to work. But anyhow with a walk in the midst of the dark forest of troubleshooting, I figured out how to properly generate the App Hash key!

Get your pre-requisites right!

First of all prepare your keystore file path, keystore alias name and keystore password, and double check those values are being properly set. This is where most of them goes wrong. Then the obvious requirement, make sure you have Androd

Method 1: On MacOS Terminal

So this is the easiest and most straight forward way to generate the hash string, by simply executing the below command on a MacOS Terminal.

keytool -exportcert -alias <keystore alias name> -keystore <keystore file with extension> | xxd -p | tr -d "[:space:]" | echo -n <your app id> `cat` | sha256sum | tr -d "[:space:]-" | xxd -r -p | base64 | cut -c1-11
  • Replace the <keystore alias name> with your keystore alias name, ex: mykeystorename
  • Replace the <keystore file with extension> with the full path to your keystore file, ex: /Users/username/Desktop/mykeystorefile.keystore
  • Replace the <your app id> with your app id: com.mytest.app

If everything went well, next line Terminal will immediately prompt you to enter the keystore password, which will generate the accurate app hash key!

Yep simple as that! 😀

Now you might wonder how I shared the above screenshot so bravely without worrying about the security, oh well its just using the default Xamarin Android keystore generated by VS for Mac with its default settings and a fake app id! 😛

Troublesome? Get Utils installed!

Unless you got some missing utils in your mac developer machine, such as the following error: sha256sum: command not found, which indicates missing coreutils in your Mac. Therefore you need to fist install Homebrew if you don’t have already.

Install Homebrew: https://brew.sh/

Restart Terminal and run the below command!

brew install coreutils

Restart Terminal and re-run the has generation command! 🙂

Method 2: On Windows CMD Prompt

Now on Windows its going to be a little bit of more work specially most of the command parameters which are used in unix cannot be executed straight up in Windows Command Prompt.

So in hope of avoiding at least a little bit of pain I would recommend using the Visual Studio Command Prompt or the Android ADB Command Prompt in your Windows PC. Specially since the java keytool path should already be configured in the Path property there.

Step 1: Generate the hex string from keystore file

keytool -alias <keystore alias name> -exportcert -keystore "<keystore file with extension>" -storepass "<keystore password>" | xxd -p

Now the parameters that you need to replace are the same as we did on MacOS command, but as you can see keystore file path and password are provided within brackets or quotations. So make sure to add that detail.

If everything went well, it will return you the hex string from your keystore file!

Now that’s me trying out the default debug keystore file in Windows. If everything executes properly, it should return a super long hex string as shown above, actually even much longer than that lol, I just cropped it out 😛

Copy that hex string and keep it, we are gonna use it in the next step.

Step 2: Implement the Hash key generate code script

Next we’re going to port the Google Doc’s Android Java implementation of the Hash key generation execution to Xamarin Android C# code snippet, thanks to my few minutes of trail and error efforts 😛


// move to the class global level
using Android.Util;
using Java.Security;
using Java.Util;
using System.Text;
// move to the class global level
private static string HASH_TYPE = "SHA-256";
private static int NUM_HASHED_BYTES = 9;
private static int NUM_BASE64_CHAR = 11;
/// <summary>
/// Generate App hash key using package
/// name and keystore hex signature
/// </summary>
/// <param name="packageName"></param>
/// <param name="keystoreHexSignature"></param>
/// <returns></returns>
public static string GetAppHashKey
(String packageName, String keystoreHexSignature)
{
string appInfo = packageName + " " + keystoreHexSignature;
try
{
MessageDigest messageDigest = MessageDigest.GetInstance(HASH_TYPE);
messageDigest.Update(Encoding.UTF8.GetBytes(appInfo));
byte[] hashSignature = messageDigest.Digest();
hashSignature = Arrays.CopyOfRange (hashSignature, 0, NUM_HASHED_BYTES);
string base64Hash = Android.Util.Base64.EncodeToString
(hashSignature, Base64Flags.NoPadding | Base64Flags.NoWrap);
base64Hash = base64Hash.Substring(0, NUM_BASE64_CHAR);
return base64Hash;
}
catch (NoSuchAlgorithmException e)
{
return null;
}
}

Simply copy that snippet into a Xamarin Android project with the specific imports mentioned at the top of the snippet. You could use this as a little helper extension method to generate the app hash key by passing in the app package name and keystore hash value that we generated in the step 1, as mentioned in the parameters.

That should work like a charm! 😀

Although keep in mind once you generate the app hash string, you should remove the keystore hex and package name hex from the code before you submit it to the app store. Google does not recommend those sensitive information inside the code as magic strings due to obvious security reasons.

Now the above code snippet can be used in either Visual Studio on Windows or Mac as long as you got the keystore hex string. 😉

TADAAA! 😀 That’s it!

You’re welcome!

Share the love! 😉 ❤

Advanced Prism Tab Navigation with MVVM & Test friendly manner in Xamarin.Forms!

If you’re looking for how to navigate inside a Xamarin.Forms Tab Page programatically in a MVVM friendly and Test-able manner, without having any XAML-Code-Behind garbage. Welcome to my post!

Keep in mind, since this is an advanced topic, there’s not going to be any step by step intro’s to Prism or MVVM or whatnot ;)!

Sneak Peak!

Here’s a little sneak peak of the outcome of it.

PERKS:

  • Switch between Child-Tabs when you are,
    • Coming into the TabbedPage
    • Already in the TabbedPage
    • Coming back to the TabbedPage
  • Fully MVVM compatible
  • Fully Test-able, yaay!
  • Binding, Commands and Interfaces FTW!
  • Almost no XAML-code-behind garbage
  • Coming back to the TabbedPage, the Child-Tab switching occurs only when the TabbedPage is actually visible

How cool is that eh! 😉

 

Woot! Let’s get started then…

My MVVM addiction…

You know me, I’m all about that MVVM & Test-able Software Architecture life forever yol! xD

Being hustling with one of the best dot net application craftsman, has made a massive impact on my perspective of software engineering, rather than just writing some code, putting some shit together and make it work. I’m extremely obsessed with architecture of any given application I develop now, long last extendability, and fully test driven approach. High quality, clean code with all of dot net standards and complete separation of Views and ViewModels.

Backstory…

So recently, I was working on this Xamarin.Forms application which was using Prism as the MVVM framework with a fully test driven architecture. There we had all of our Views and ViewModels separately implemented with a clean architecture, whereas we didn’t have a single line of extra XAML-code-behind garbage. 😛

So the requirement was to implement a TabbedPage and which should be able to switch between its Child-Tabs programatically at runtime, to be more specific, we should be able switch the selected Child-Tab when the user is:

  • Coming into the TabbedPage
  • Already in the TabbedPage
  • Coming back to the TabbedPage after navigating forward.

And the most interesting part was this we had to handle this in a fully MVVM and Testable manner. 😮

Now this would have been much easier, if you had taken out the whole MVVM and Test-first aspect out of the equation, with some dirty XAML-code-behind garbage you can easily handle this. But in this situation, I was backed against the wall, How on earth could anyone achieve this?

but as usual, I figured it out!

The Recipe time…

So here’s how I implemented it, in conclusion we’re going to use an Interface that will allow us to bridge the View-ViewModel separation and a Bindable property inside the TabbedPage, that will react to the changes of the ViewModel’s “SelectedTab” property.

That interface is going to be implemented into the ViewModel. Then through the ViewModel we’re going to register that whole instance in our IoC container, when the user navigates into the TabbedPage. The bindable-property of the TabbedPage will be bound to the property in ViewModel. 😀

Which will allow us to access the interface instance from the IoC container from anywhere in our code and change the Selected Child-Tab.

Oh also I forgot to mention that with Prism, by default we can set the selected Tab-Child when we ‘first navigate into the Tab Page’, so handling that scenario is going to be a no-brainer, thus I will not focus on it in this post.

We shall work on navigating inside the TabbedPage when we’re already inside it, and when we’re coming back to the TabbedPage from another page after navigating forward. Which is going to be a piece of cake with our interface implementation approach.

Just to add something extra, we will maintain a flag property inside the TabbedPage, to make sure to allow the Selected Child-Tab switching happens only when the TabbedPage is visible to the user. Just to make it look nicer!

Since all of this is a simple combination of Bindable-Properties, Interfaces and Commands, this whole implementation is fully test-able. Yeah fine, I’ll show you how to write some tests for it as well! 😛

Sounds pretty straight forward eh! 😀 time for coding! 😉

Implementation time…

So just a heads up, my project configuration is as follows.

I’m using a Xamarin.Forms project (dot net Standard 2.0) created with Prism Templates for Visual Studio. And the IoC container is the default Unity container comes with Prism.Forms setup. As of the Tests I’m using a xUnit Dot net project, which I will get into details later.

So before you begin make sure you have the above setting in place.

1. interface to save the day…

First, the simple Interface which is going to save the day like we discussed above…

public interface IMyTabbedPageSelectedTab
{
	int SelectedTab { get; set; }

	void SetSelectedTab(int tabIndex);
}

 

There we have a SelectedTab property, and a separate setter method for it, just in case for backup scenario. If you don’t need both then stick to one of them. 😀

2. the TabbedPage…

Alright then let’s get started with our TabbedPage implementation, let’s call it MyTabbedPage.

<TabbedPage
    x:Class="AdvPrismTabNavigation.Views.MyTabbedPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:AdvPrismTabNavigation.Views;assembly=AdvPrismTabNavigation"
    xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
    Title="{Binding Title}"
    prism:ViewModelLocator.AutowireViewModel="True"
    SelectedTabIndex="{Binding SelectedTab}">
    <TabbedPage.Children>
        <local:TabChild1Page />
        <local:TabChild2Page />
        <local:TabChild3Page />
    </TabbedPage.Children>
</TabbedPage>

 

There’s the XAML code for our MyTabbedPage, notice how we’re binding the SelectedTabIndex property to the ViewModel’s property which I’ll show later in this post. Meanwhile let’s have add some child pages to our MyTabbedPage as well.

Alright next take a look at the MyTabbedPage‘s code behind stuff, which is very minimal.

public partial class MyTabbedPage : TabbedPage
{
	private bool _isTabPageVisible;

	...
        // SelectedTabIndex 
	// bindable property goes here...
	...

	public MyTabbedPage()
	{
		InitializeComponent();
	}
	
	protected override void OnAppearing()
	{
		base.OnAppearing();

		// the tabbed page is now visible...
		_isTabPageVisible = true;

		// go ahead and update the Selected Child-Tab page..
		this.CurrentPage = this.Children[SelectedTabIndex];
	}

	protected override void OnDisappearing()
	{
		base.OnDisappearing();

		// the Tabbed Page is not visible anymore...
		_isTabPageVisible = false;
	}

	protected override void OnCurrentPageChanged()
	{
		base.OnCurrentPageChanged();

		// when the user manually changes the Tab,
		// we need to update it back to the ViewModel...
		SelectedTabIndex
			= this.Children.IndexOf(this.CurrentPage);
	}
}

 

As I mentioned in the recipe, there’s the flag _isTabPageVisible, we’re going to use to keep track of the Visibility of the TabbedPage. There when we’re coming back to the TabbedPage from a backward navigation, we’re executing the selected Child-Tab according to the SelectedTabIndex bindable property.

Important Note: You can even make the above little chunks of code go away from the XAML-Code-behind, by using triggers and attached properties, which I’m not going to get into here, to maintain the simplicity of the implementation. Come on, use your own creativity people! 😉

Next we’re creating the Bindable Property inside the TabbedPage which will handle the View-ViewModel communication. Let’s call it SelectedTabIndex property.

public static readonly BindableProperty SelectedTabIndexProperty =
	BindableProperty.Create(
		nameof(SelectedTabIndex), 
		typeof(int),
		typeof(MyTabbedPage), 0,
		BindingMode.TwoWay, null,
		propertyChanged: OnSelectedTabIndexChanged);
static void OnSelectedTabIndexChanged
	(BindableObject bindable, object oldValue, object newValue)
{
	if (((MyTabbedPage)bindable)._isTabPageVisible)
	{
		// update the Selected Child-Tab page 
		// only if Tabbed Page is visible..
		((MyTabbedPage)bindable).CurrentPage 
		= ((MyTabbedPage)bindable).Children[(int)newValue];
	}
}
public int SelectedTabIndex
{
	get { return (int)GetValue(SelectedTabIndexProperty); }
	set { SetValue(SelectedTabIndexProperty, value); }
}

 

Looks neat eh, so its a simple Bindable property as you can see, but however we’re handling it’s OnSelectedTabIndexChanged event ourselves because when the value changes from ViewModel’s end we need to update it on our UI’s end, as you can see we’re having a little flag property inside our MyTabbedPage 

3. the ViewModel…

Now is the time for MyTabbedPageViewModel stuff to come along. Nothing fancy just a standard ViewModel, but we need a reference to the IoC container (whichever it is you’re using) because we need to register our interface instance in it. This ViewModel as we discussed before is going to implement our IMyTabbedPageSelectedTab interface and its method and property.

public class MyTabbedPageViewModel 
          : ViewModelBase, IMyTabbedPageSelectedTab
{
     private readonly IUnityContainer _unityContainer;

     private int _selectedTab;
     /// <summary>
     /// Binds to the View's property
     /// View-ViewModel communcation
     /// </summary>
     public int SelectedTab
     {
          get { return _selectedTab; }
          set
          {
             SetProperty(ref _selectedTab, value);
             Title = $"My Tabbed Page - Tab [{SelectedTab + 1}]";
          }
     }
     
     public MyTabbedPageViewModel
          (INavigationService navigationService,
                         IUnityContainer unityContainer)
          : base(navigationService)
     {
          Title = $"My Tabbed Page - Tab [{SelectedTab + 1}]";

          this._unityContainer = unityContainer;

          // register this instance so we can access 
          // IMyTabbedPageSelectedTab anywhere in the code
          _unityContainer.RegisterInstance<IMyTabbedPageSelectedTab>
                    (this, new ContainerControlledLifetimeManager());
     }

     public void SetSelectedTab(int tabIndex)
     {
          SelectedTab = tabIndex;
     }
}

 

The SelectedTab property in the ViewModel is the one that’s binding to the SelectedTabIndex property in the MyTabbedPage, now you can see the bridge between the View-ViewModel.

Here we’re registering this ViewModel instance by the type of IMyTabbedPageSelectedTab so that we can access it from anywhere using the same type and also we’re passing in ContainerControlledLifetimeManager() parameter because we need to make sure that instance is properly managed by the container and garbage collected later when not in use.

4. finally Consume it…

So here is the little Magic code snippet you need to execute, wherever you wish to have access to programatically switching the Selected Child-Tab of our MyTabbedPage.

_unityContainer.Resolve<IMyTabbedPageSelectedTab>().SetSelectedTab(tabIndex);

 

You simply access the registered service interface and call on the SetSelectedTab() or simply you could also call the IMyTabbedPageSelectedTab.SelectedTab property directly as well. 😉

Just a little note, well this may not be the best of all approaches but this is what I believe is a better solution given my experience and expertise. But if you have a better alternative, please feel free to share!

Let’s fire it up!

So here’s this bad boy in action…

 

That’s the Child-Tab being switched programatically while inside the TabbedPage!

 

And here’s how nicely the Child-Tabs are switching programatically while outside the TabbedPage! As you can see when coming back to the TabbedPage, it nicely moves to the Selected Child-Tab…

Eyyy look at that! 😀

How about UnitTest-ing…

Uh fine, let me show you. 😛

In my case I used xUnit.net for my Test project, along side Prism.Forms and Xamarin.Forms.Mocks for mocking Xamarin.Forms run time.

Switching between Child-Tabs inside the TabbedPage:

//  Let's Tab-Navigate to TabChild2Page
_appInstance.Container.Resolve<TabChild1PageViewModel>()
			.GoToNextTabCommand.Execute("1");

//  Am I in the MyTabbedPage-> TabChild2Page?
Assert.IsType<TabChild2PageViewModel>
			(myTabbedPage.CurrentPage.BindingContext);

//  Let's Tab-Navigate to TabChild3Page
_appInstance.Container.Resolve<TabChild2PageViewModel>()
			.GoToNextTabCommand.Execute("2");

//  Am I in the MyTabbedPage-> TabChild2Page?
Assert.IsType<TabChild3PageViewModel>
			(myTabbedPage.CurrentPage.BindingContext);

 

I’m calling the Commands through my child page’s ViewModel and switching the Selected Child-Tab and then asserting to make sure the myTabbedPage instance has updated accordingly.

Switching between Child-Tabs outside the TabbedPage:

//  Am I inside the DetailPage?
Assert.IsType<DetailPageViewModel>
		    (navigationStack.Last().BindingContext);

// Let's go back to Tabbed Page -> TabChild3Page
_appInstance.Container.Resolve<DetailPageViewModel>()
		    .GoBackToTabChild3PageCommand.Execute();

//  Am I inside the MyTabbedPage?
Assert.IsType<MyTabbedPageViewModel>
		    (navigationStack.Last().BindingContext);

//  Am I in the MyTabbedPage-> TabChild3Page?
Assert.IsType<TabChild3PageViewModel>
		    (myTabbedPage.CurrentPage.BindingContext);

 

Here you can clearly see I’m calling the GoBackToTabChild3PageCommand in an page(DetailPage) which Ihave navigated to after the TabbedPage, and what happens in that command is I’m changing the Selected Child-Tab in the MyTabbedPage and immediately going back to it by exiting the DetailPage. Then I’m coming back to the MyTabbedPage, and the Child-Tab 3 is selected in the TabbedPage.

Here’s where you could take a look at the full test implementation : https://github.com/AdvPrismTabNavigation.xUnitTest

Voila! 😀 UnitTest-ing Done!

Github it if yo lazy!

So all of this is hosted on my git repo: https://github.com/AdvPrismTabNavigation

Feel free to grab your copy if you’re too lazy to DIY! 😛

That’s it for today.

Cheers all! 😀 Share the love!

Build yo own awesome Activity/Loading Indicator Page for Xamarin Forms…

Have you ever wanted to have an Activity or Loading indicator dialog screen overlay, that is transparent, and fully customized by you? in your Xamarin.Forms project?

Then you stopped at the right place.

Today I’m gonna share how to build a fully customizable Activity Indicator /Loading Screen from Xamarin.Forms with a bit of native magic. To be honest, more of a continuation of my previous blog post! 😉 lol

Perks:

  • Fully customizable View on the go from Xamarin.Forms
  • Overlays on top of your ContentPage / Navigation Stack
  • Service based, full MVVM & testing friendly
  • Fully transparent and controllable dimmer
  • Cancellation & back button disabled

Here’s a sneak peek…

  

TADAAA! That’s what yol gonna build! 😀

The Concept…

So basically if you think about it, when you want to display an Loading/Activity indicator overlay screen, it is something that would indicate,

“Oh there’s some important processing going on that Page and we need you to wait until it finishes…” 😛

“In the meantime we’re going to block the interactivity of that Page with this overlay, but you can still see the progress of it with the transparency…”

So in the language of Xamarin.Forms, on top of your ContentPage, we need something that would block the interactivity of background content but allows us to see what’s going in the background, in other words, it should be a transparent or dimmed View. 😀

A ghost from the past…

So I’m going to revert your attention to the previous blog post I wrote, Build your own Transparent Page from scratch for Xamarin.Forms, which was all about creating a Transparent page for Xamarin.Forms using a bit of native code. And I’ll be using the same concept and the code here as well, but I’m not going to drill down to the technical details of that specific implementation here, so if you’re looking for it, go ahead and give it a read first and come back.

The Recipe time…

So if you’re coming back  from my previous blog post you could probably consider this post as a continuation of it. Today we’re going to create a Transparent Page in Xamarin.Forms using a bit of native magic, that will overlay on top of any Xamarin.Forms ContentPage or the Navigation Stack, and has the capability to customize the Transparent content view on demand. 😀

So to do this, we’re going to implement a native Transparent page in our Platform projects (iOS and Android), then we’re going to create a Service implementation that can display and dismiss our Transparent pages on demand while being able to pass in the desired Content View as we wish to display as parameters. The actual concrete implementation of that service will bed laid down in platform specific projects, along side the native Transparent page rendering implementation. So that we can do the rendering or displaying or dismissing our Loading/Activity indicator overlay on demand as we wish.

So to map the Service interface and its concrete implementations we are going to use Xamarin.Forms Dependency service, but then if you have your own IoC container you could use it as well. 😉

Sounds pretty straight forward eh! 😀 time for coding! 😉

Xamarin.Forms bits…

Alright then let’s hit it with the Service interface implementation. Let’s call it ILodingPageService.

public interface ILodingPageService
{
	void InitLoadingPage
                  (ContentPage loadingIndicatorPage = null);

	void ShowLoadingPage();

	void HideLoadingPage();
}

 

So we will have three interface methods, one to initiate and prepare the Transparent page we’re going to display as our Loading/Activity indicator overlay. Then two more to Show it or Hide it on the app.

Speaking of InitLoadingPage() method, the reason we need is to facilitate the feature of displaying different Loading pages or designs on demand at the run time. So let’s say in Page 1 we want to display one Loading page, then in Page 2 we want to display a different kind of Loading Page, that right there is possible here with this method. You just pass in whatever the Loading Page design you want to show, and you’re done! 😉 How cool is that!

Since this a Xamarin.Forms Transparent Page, let’s first create our usual ContentPage, with usual stuff. Let’s call it the LoadingIndicatorPage1

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="XFLoadingPageService.LoadingIndicatorPage1"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    BackgroundColor="#80000000">
    <ContentPage.Content>
        <StackLayout
            Padding="30"
            BackgroundColor="Black"
            HorizontalOptions="Center"
            VerticalOptions="Center">
            <ActivityIndicator IsRunning="True" Color="White" />
            <Label
                FontAttributes="Bold"
                Text="Loading..."
                TextColor="White" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

 

So you can see we have a very simple ContentPage design, with an ActivityIndicator and a Label to show that, “Oh look it’s a loading screen… boo!” lol 😀

Android bits….

Here come the actual magic, let me begin with Android! So let’s start off with our ILoadingPageService’s concrete implementation for Android and register it with the Xamarin Dependency Service.

[assembly: Xamarin.Forms.Dependency(typeof(LodingPageServiceDroid))]
namespace XFLoadingPageService.Droid
{
    public class LodingPageServiceDroid : ILodingPageService
    {
        private Android.Views.View _nativeView;

        private Dialog _dialog;

        private bool _isInitialized;

        public void InitLoadingPage(ContentPage loadingIndicatorPage)
        {
            // check if the page parameter is available
            if (loadingIndicatorPage != null)
            {
                // build the loading page with native base
                loadingIndicatorPage.Parent = Xamarin.Forms.Application.Current.MainPage;

                loadingIndicatorPage.Layout(new Rectangle(0, 0,
                    Xamarin.Forms.Application.Current.MainPage.Width,
                    Xamarin.Forms.Application.Current.MainPage.Height));

                var renderer = loadingIndicatorPage.GetOrCreateRenderer();

                _nativeView = renderer.View;

                _dialog = new Dialog(CrossCurrentActivity.Current.Activity);
                _dialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                _dialog.SetCancelable(false);
                _dialog.SetContentView(_nativeView);
                Window window = _dialog.Window;
                window.SetLayout(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
                window.ClearFlags(WindowManagerFlags.DimBehind);
                window.SetBackgroundDrawable(new ColorDrawable(Android.Graphics.Color.Transparent));

                _isInitialized = true;
            }
        }

        public void ShowLoadingPage()
        {
            // check if the user has set the page or not
            if (!_isInitialized)
                InitLoadingPage(new LoadingIndicatorPage1()); // set the default page

            // showing the native loading page
            _dialog.Show();
        }

        public void HideLoadingPage()
        {
            // Hide the page
            _dialog.Hide();
        }
    }
}

 

Most of the above Xamarin Android specific code is already explained in detailed line by line in my previous post. So in short, here we have the concrete implementation of our service for Android, inside the InitLoadingPage() we’re passing in the Xamarin.Forms Page which we want to render as a transparent page which will act as our Activity Indicator.  Then we’re rendering that page and embed into a Android Dialog view with a transparent background, and back button cancelled properties enabled. We’re keeping a reference of the _dialog instance so that we can show or hide the Page upon respective ShowLoadingPage() and HideLoadingPage() executions.

So every time a user wants to display a different Loading page, they will call the InitLoadingPage() which will build the new page instance and keep it in the service memory.

At the same time you may have seen inside ShowLoadingPage() if you haven’t instantiated the transparent page, then we’re using a default page, LoadingIndicatorPage1 as a template ad instantiating it on the go, just to avoid exceptions. This choice of default page is totally up to you.

Also don’t forget at the top of the namespace we’re registering this concrete implementation with Xamarin Dependency service. 😉

iOS bits….

Then let’s move on with our ILoadingPageService’s concrete implementation for iOS and register it with the Xamarin Dependency Service.

[assembly: Xamarin.Forms.Dependency(typeof(LodingPageServiceiOS))]
namespace XFLoadingPageService.iOS
{
    public class LodingPageServiceiOS : ILodingPageService
    {
        private UIView _nativeView;

        private bool _isInitialized;
        
        public void InitLoadingPage(ContentPage loadingIndicatorPage)
        {
            // check if the page parameter is available
            if (loadingIndicatorPage != null)
            {
                // build the loading page with native base
                loadingIndicatorPage.Parent = Xamarin.Forms.Application.Current.MainPage;

                loadingIndicatorPage.Layout(new Rectangle(0, 0,
                    Xamarin.Forms.Application.Current.MainPage.Width,
                    Xamarin.Forms.Application.Current.MainPage.Height));

                var renderer = loadingIndicatorPage.GetOrCreateRenderer();

                _nativeView = renderer.NativeView;

                _isInitialized = true;
            }
        }

        public void ShowLoadingPage()
        {
            // check if the user has set the page or not
            if (!_isInitialized)
                InitLoadingPage(new LoadingIndicatorPage1()); // set the default page

            // showing the native loading page
            UIApplication.SharedApplication.KeyWindow.AddSubview(_nativeView);
        }

        public void HideLoadingPage()
        {
            // Hide the page
            _nativeView.RemoveFromSuperview();
        }
    }
}

 

So the implementation here is also similar to Android code above, except for the native bit. So we’re instantiating the Xamarin.Forms Page instance inside, InitLoadingPage() method we’re initiating the transparent page instance and holding inside the service.

Then showing it or hiding it based on the ShowLoadingPage() or HideLoadingPage() calls.

Pretty straightforward eh! 😀

So what next…

Now one of the best features of this implementation is that your could use any number of Loading Indicator Pages as you wish with various kinds of designs. 😀 So just for the kicks of it here’s another page that we’ll use. let’s call it LoadingIndicatorPage2

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="XFLoadingPageService.LoadingIndicatorPage2"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    BackgroundColor="#80000000">
    <ContentPage.Content>
        <StackLayout
            Padding="30"
            BackgroundColor="#D93463"
            HorizontalOptions="Center"
            VerticalOptions="Center">
            <ActivityIndicator IsRunning="True" Color="White" />
            <Label
                FontAttributes="Bold"
                Text="Yo! Hold on..."
                TextColor="White" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

 

If that’s not enough you can add more and more as you go 😀 but just make sure to call the InitLoadingPage() method! 😉

Let’s fire it up…

So to fire this up we need to call this service from your Xamarin.Forms code using the DependencyService.

// show the loading page...
DependencyService.Get<ILodingPageService>()
                 .InitLoadingPage(new LoadingIndicatorPage1());
DependencyService.Get<ILodingPageService>().ShowLoadingPage();

 

There we’re first initiating our page and then show it on the app. Once you initiate the page you don’t have to call it ever again as you saw in the implementation, it is retained in the memory of the service.

// close the loading page...
DependencyService.Get<ILodingPageService>().HideLoadingPage();

 

Once you’re done, you can close our awesome Activity / Loading Indicator Page with the above code.

And here we go on iOS and Android in action…. 😀

That’s our first Loading screen in action…

And click on the second button, there’s our second Loading screen in action, on the go…

Look at that, even during navigation between pages our Loading page stays intact on top of the Xamarin.Forms Pages stack. 😉

The reason why it acts so independently is because we are directly accessing the native elements in the service implementation, therefore even during navigation of Xamarin.Forms Stack or whatever the UI activity our Loading page will not be affected, it will keep on, of its own.

How awesome is that eh! 😀

Github it if yo lazy!

So all of this is hosted on my git repo: https://github.com/XFLoadingPageService

Now your own imagination is the limit for what’s possible or not fellas!

That’s it for today.

Cheers! 😀

Build your own Transparent Page from scratch for Xamarin.Forms…

There was this one time I wanted to build my own Transparent Page in Xamarin Forms, from scratch, all by myself, due to my ego and to challenge myself.

Usually when it comes to Transparent page related situations I would always recommend the awesome Rg.Plugins.Popup  library, which I had praised one of my previous blog posts as well, So I created a Popup with Transparent background in Xamarin Forms… 😉

Backstory…

But for real there was one instance I couldn’t use any 3rd party library for the project and all the code bits should be from scratch. So I had no option but to resort myself to creating my own Transparent Page in that Xamarin.Forms project.

And I did…

Sneak Peak…

So this how it would look like.

And limit of the expansion is all up to your imagination and developer skills.

If not work on it! 😛

Recipe time!

So to create a transparent page in Xamarin.Forms out of the box is impossible, which I’m not going to explain in detail. Obviously in short, for reasons such as Xamarin.Forms abstracts the most common subset of properties of the native platforms, we don’t have much power of customization of the UI.

There is no way to use Xamarin.Forms ContentPage with transparency. (Yes I have tried!) So we need something beyond Xamarin.Forms stuff, Aha! Natively Rendered View, that could overlay on top of a give ContentPage.

But that doesn’t mean Xamarin.Forms would block you from implementing something platform specific, it only empowers you 😉

Also since we’re drilling down in the native levels, we have absolute control over Xamarin.Forms Pages, including the power to push any View on top of Xamarin.Forms ContentPage Navigation stack.

Recipe in-depth!

So to do this we need to have some Native platform level access, so if you’re using a Xamarin.Forms shared project, this should be pretty easy, but for PCL projects, you may have to create a dependency service implementation to invoke this implementation.

So in Android, we’re going to use Dialog View to implement the transparent Page and with the access of the Activity instance, we’ll push it to over any give ContentPage of Xamarin.Forms.

Then in iOS, we’ll be using UIApplication instance’s KeyWindow property to push the transparent Page over any given ContentPage of Xamarin.Forms.

Sounds pretty straight forward eh! 😀

Xamarin.Forms bits…

Alright since this a Xamarin.Forms Transparent Page, let’s first create our usual ContentPage, with usual stuff.

var xamFormsPage = new ContentPage() 
{
  BackgroundColor = new Color(0, 0, 0, 0.5),
  Content =
  new StackLayout() 
  {
    Padding = 30,
    Spacing = 20,
    WidthRequest = 250,
    BackgroundColor = Color.Black,
    Children = 
	{
	 new Xamarin.Forms.Label() {
	  Text =
	   "Welcome to my own Transparent Page!",
	   FontAttributes = FontAttributes.Bold,
	   TextColor = Color.White,
	   FontSize = 20,
	 },
	 new Xamarin.Forms.Label() {
	  Text =
	   "This is from Xamarin.Forms with a " +
	   "bit mix of simple native magic!",
	   TextColor = Color.White,
	   FontSize = 17,
	 },
	 new Xamarin.Forms.Button() {
	  Text = "Close me!",
	   BackgroundColor = Color.Gray,
	   TextColor = Color.White,
	 }
    },
    VerticalOptions = LayoutOptions.Center,
    HorizontalOptions = LayoutOptions.Center,
  }
};

 

So here we have an instance of a simple Xamarin.Forms.Content page, with a bunch of labels and a button. This is the page we’re going to render into a transparent page. 😉

Android Implementation…

So like we discussed before, on Android we’re going to make use of the Android Dialog View to populate our transparent page. In order to do this we need to get access to the current Activity of our Xamarin.Forms Android run time.

In order to do that we’re going to use CrossCurrentActivity plugin by James Montemagno. So before we begin, go ahead and add that plug in to your Xamarin.Forms solution using Nuget.

Now the basic idea here is all about actually rendering our Xamarin.Forms ContentPage instance, and converting it to a native Android View at run time. Then we take that native View instance and attach into a Android Dialog View, making it visible along with the transparent effect. Oh yes the CrossCurrentActivity plugin comes handy when we instantiate our Android Dialog View. 😉

// Assign the Parent hook for our page instance 
xamFormsPage.Parent = Xamarin.Forms.Application.Current.MainPage;

// Run the Layout Rendering Cycle for the page
xamFormsPage.Layout(new Rectangle(0, 0,
 Xamarin.Forms.Application.Current.MainPage.Width,
 Xamarin.Forms.Application.Current.MainPage.Height));

// Get the native renderered instance for our page
var nativePageRendererInstance = xamFormsPage.GetOrCreateRenderer();

// Get the native page for our page
Android.Views.View nativePageView = nativePageRendererInstance.View;

// Create the native transparent Dialog instance to embed our page
Dialog dialog = new Dialog(CrossCurrentActivity.Current.Activity);
dialog.RequestWindowFeature((int) WindowFeatures.NoTitle);
dialog.SetCancelable(false);
dialog.SetContentView(nativePageView);
Window window = dialog.Window;
window.SetLayout(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
window.ClearFlags(WindowManagerFlags.DimBehind);
window.SetBackgroundDrawable(new ColorDrawable(Android.Graphics.Color.Transparent));

// Show the page
dialog.Show();

 

There you have the magical code 😉 lol.

You can see how we’re setting the Parent hook to our Xamarin.Forms page instance, then running the Layout() rendering circle allowing the Views to be actually measured and rendered in the memory. Then we convert our Xamarin.Forms page instance into a native Android View using the GetOrCreateRenderer() extension method which I will describe next.

Then as I discussed before we’re attaching the native View into a Dialog View and setting it visible resulting in total awesome transparency of a page, along with the exact Xamarin.Forms content we wanted to display.

Oh before I forget here is the precious Xamarin.Forms.View -> Android.Views.View Converter extension implementation. Special thanks to rotorgames for the below magical code block. 😉

internal static class PlatformExtension
{
	public static IVisualElementRenderer GetOrCreateRenderer(this VisualElement bindable)
	{
		var renderer = XFPlatform.GetRenderer(bindable);
		if (renderer == null)
		{
			renderer = XFPlatform.CreateRendererWithContext(bindable, CrossCurrentActivity.Current.Activity);
			XFPlatform.SetRenderer(bindable, renderer);
		}
		return renderer;
	}
}

Source Credit: Rg.Plugins.Popup.Droid/PlatformExtension.cs

As you can see it’s a simple implementation that takes in the Xamarin.Forms View instance and retrieve the native renderer for that View.

Now when you need to hide the above Transparent page, you simply call Hide() on the Android Dialog instance.

// Hide the page
dialog.Hide();

 

Then we go to the iOS stuff..

iOS Implementation….

Here we’ve come to the iOS implementation, so just like we discussed in the beginning, we’re going to access the global UIApplication singleton to push our transparent page the application view through the KeyWindow property.

So in a nutshell iOS renders every native View with the transparency give the proper background spacing, so we don’t really have to worry about using any placeholder view. The idea here is to get our Xamarin.Forms Page instance, run its Layout rendering cycle, convert that instance to an iOS native View. Then finally push it to the KeyWindow property by adding as a SubView.

Pretty straightforward, almost similar as to what we did in Android but simpler! 😉

// Assign the Parent hook for our page instance 
xamFormsPage.Parent = Xamarin.Forms.Application.Current.MainPage;

// Run the Layout Rendering Cycle for the page
xamFormsPage.Layout(new Rectangle(0, 0,
 Xamarin.Forms.Application.Current.MainPage.Width,
 Xamarin.Forms.Application.Current.MainPage.Height));

// Get the native renderered instance for our page
var nativePageRendererInstance = xamFormsPage.GetOrCreateRenderer();

// Get the native page for our page
UIView nativePageView = nativePageRendererInstance.NativeView;

// Show the page by pushing to the stack
UIApplication.SharedApplication.KeyWindow.AddSubview(nativePageView);

 

I’m not going repeat myself here because I’m too lazy and the explanation is almost same as I did in Android implementation. 😀

But in the context of iOS, you can see we’re getting the iOS native UIView of our Xamarin.Forms ContentPage instance and pushing it directly to the Application UI, by calling AddSubView() on KeyWindow property.

Oh before I forget here is the precious Xamarin.Forms.View -> UIKit.UIView Converter extension implementation. Special thanks to rotorgames for the below magical code block. 😉

internal static class PlatformExtension
{
	public static IVisualElementRenderer GetOrCreateRenderer(this VisualElement bindable)
	{
		var renderer = XFPlatform.GetRenderer(bindable);
		if (renderer == null)
		{
			renderer = XFPlatform.CreateRenderer(bindable);
			XFPlatform.SetRenderer(bindable, renderer);
		}
		return renderer;
	}
}

Source Credit: Rg.Plugins.Popup.IOS/PlatformExtension.cs

Now when you want to hide the above created Transparent Page, then you simple call the RemoveFromSuperview() on our iOS UIView instance, which will result in it removing itself from UIWindow.

// Hide the page
nativePageView.RemoveFromSuperview();

 

bloopity blah! 😀

Alright, so let me address something you might be wondering…

How about Xamarin.Forms to Xamarin Native bridge?

Now you might ask how am I going to bridge the above explained Xamarin.Forms and Xamarin Native implementation counterparts together? Now that’s some easy peasy nibbles I’m gonna leave up to your creativity or requirement.

There’s many ways to call back and forth between Xamarin.Forms or Xamarin Native project levels, or in other words, between the PCL project and the Platform Specific projects. For starters, you could use Xamarin Dependency Service to register a service interface and concrete implementation to communicate between these two layers back and forth. 😉 And many other possibilities, so your creativity is the limit.

However I will probably be writing another blog post regarding this with a full implementation of this with some cool application of it! 😉

Well frankly, that’s it fellas.

Cheers! 😀

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!

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