Monthly Archives: February 2017

Fancy Me! Here’s a Label with Rounded Corners in Xamarin Forms…

Time for something fancy, a Label with Rounded corners in Xamarin Forms! 😉

Why you’d ask? Well why not!

Sneak peak…

screenshot-1

Well look how cool that is yeah. So let’s see how we could do this.

Let the coding begin…

So as usual let’s sub-class our custom Label from the default Xamarin Forms Label control.

namespace WhateverYourNamespace
{
    public class CurvedCornersLabel : Label
    {
        ...
    }
}

 

some custom properties?

Yep we are going to be needing some custom properties to define the Radius value for the corners of the Label and then the background color for the Curved background, well of course you could use the default BackgroundColor property, but where’s the fun in that? lol 😛

public static readonly BindableProperty CurvedCornerRadiusProperty =
	BindableProperty.Create(
		nameof(CurvedCornerRadius),
		typeof(double),
		typeof(CurvedCornersLabel),
		12.0);
public double CurvedCornerRadius
{
	get { return (double)GetValue(CurvedCornerRadiusProperty); }
	set { SetValue(CurvedCornerRadiusProperty, value); }
}


public static readonly BindableProperty CurvedBackgroundColorProperty =
	BindableProperty.Create(
		nameof(CurvedCornerRadius),
		typeof(Color),
		typeof(CurvedCornersLabel),
		Color.Default);
public Color CurvedBackgroundColor
{
	get { return (Color)GetValue(CurvedBackgroundColorProperty); }
	set { SetValue(CurvedBackgroundColorProperty, value); }
}

 

Now add the above properties inside the Custom control we just created above. As you can see as the default Radius we are setting value 12, if no explicit values were given this will be set as the corner radius of the Label. 🙂

Android stuff…

Let’s dig into the Android Renderer for our fancy Label 😉

So the Android TextView, which is the native control that corresponds with Xamarin Forms Label at run time,  doesn’t have a corner radius property.

So in order to create a Curved background in TextView we need to add Background Drawable layer.

Preferably a GradientDrawable which has the CornerRadius property where we could use to manipulate the curved corners as the background for our Label. Perfecto!

[assembly: ExportRenderer(typeof(CurvedCornersLabel), typeof(CurvedCornersLabelRenderer))]
namespace WhateverYourNamepsace.Droid
{
public class CurvedCornersLabelRenderer : LabelRenderer
{
	private GradientDrawable _gradientBackground;

	protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
	{
		base.OnElementChanged(e);

		var view = (CurvedCornersLabel)Element;
		if (view == null) return;

		// creating gradient drawable for the curved background
		_gradientBackground = new GradientDrawable();
		_gradientBackground.SetShape(ShapeType.Rectangle);
		_gradientBackground.SetColor(view.CurvedBackgroundColor.ToAndroid());
		
		// Thickness of the stroke line
		_gradientBackground.SetStroke(4, view.CurvedBackgroundColor.ToAndroid());
		
		// Radius for the curves
		_gradientBackground.SetCornerRadius(
			DpToPixels(this.Context,
			Convert.ToSingle(view.CurvedCornerRadius)));

		// set the background of the label
		Control.SetBackground(_gradientBackground);
	}

	/// <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);
	}
}
}

 

So there you have it, we create a Drawable object with the Rectangle shape, and then we set the required properties such as Stroke Color and Corner Radius.

Now you may have noticed that I’m using exact Pixel values for the Radius value from the DpToPixels() method, this is to ensure the Radius value supports as many devices as possible without distorting the expected curve shape. And if you read my previous post, I have already talked about Device Independent Pixels and actual Device Pixels: DpToPixels and PixelsToDp for Xamarin Android…

Once the Drawable object is configured, we set it as the Background of the Label 🙂

iOS stuff…

Next is the iOS renderer for our control.

For iOS we have the UILabel that corresponds with the Xamarin Forms Label control at run time, now for the luck of it UILabel already has a property that associates with Radius of the corners, via the Layer property. So we could directly render the curved corners through those properties.

[assembly: ExportRenderer(typeof(CurvedCornersLabel), typeof(CurvedCornersLabelRenderer))]
namespace WhateverYourNamepsace.iOS
{ 
    public class CurvedCornersLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                var _xfViewReference = (CurvedCornersLabel)Element;
				
		// Radius for the curves
                this.Layer.CornerRadius = (float)_xfViewReference.CurvedCornerRadius;
				
                this.Layer.BackgroundColor = _xfViewReference.CurvedBackgroundColor.ToCGColor();
            }
        }
    }
}

 

There we go, we set the Layer’s CornerRadius property with our CurvedCornerRadius value and the background color to the Layer.

Let’s try it out…

Now let’s consume this sweetness…

<StackLayout VerticalOptions="CenterAndExpand">

	<Label
	  Text="this is a normal Label"
	  HorizontalTextAlignment="Center"
	  VerticalTextAlignment="Center"
	  FontSize="14.5"
	  HeightRequest="30"
	  BackgroundColor="#20a9f8"
	  TextColor="White"/>

	<local:CurvedCornersLabel
	  Text="this is a rounded Label"
	  HorizontalTextAlignment="Center"
	  VerticalTextAlignment="Center"
	  FontSize="14.5"
	  HeightRequest="30"
	  CurvedBackgroundColor="#0040ff"
	  TextColor="White"
	  CurvedCornerRadius="15">
	</local:CurvedCornersLabel>

</StackLayout>  

 

Don’t be shy and use our awesome CurvedCornersLabel control we just created! 😀

Hit F5 and Run this thing man!

screen-shot-2017-02-19-at-12-17-13-pm  nexus-5-lollipop-screenshot-2

BEHOLD THE FANCINESS!

😀

Cheers everyone, enjoy!

PS: For them lazy ones, you may grab my github commit from here: Xamarin-Playground/XFCurvedCornersLabelControl

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

“UnpackLibraryResources” or “MTouch” task failed, during compile?

Now this is regarding the mysterious build error, “UnpackLibraryResources” task failed and the “MTouch” task failed, which unfortunately occurs out of nowhere in Xamarin Forms projects…

It all started…

So sometimes when I try to build and run my perfect Xamarin Forms project in Visual Studio, by the way which has no compilation issues, suddenly breaks down with a compilation error saying “UnpackLibraryResources” task failed and the “MTouch” task failed…
This was a complete puzzle to me, since there were no errors in the code, and this never occurred with any small scale project solutions, only with those massive enterprise scale projects at work.

I tried to look for a solution…

So I tried clean and rebuild, reopen Visual Studio, and blah blah many things.

Weirdly enough…

So one last destination I tried was restarting Windows and re-opening Visual Studio, which actually worked!
It got me thinking, may be this has to do something with the resource usage of the PC, may be the build process is getting disturbed by some system activity in the background.

then I found this…

So I opened up Task Manager, and kept an eye on it, while running the compile and rebuild of my project.

BOOM! 😮

I stumbled upon a crazy observation, whereas every time the above error occurs and the build fails, the Disk usage was showing up as below in the Task Manager.

unpacklibraryresources-compilation-error

And then time during the following error I noticed the same Disk usage as well.

mtouch-task-failed-compilation-error

Its very rare that VS could cause such a massive disk usage during build and run, and even if it did, why would the build process fail in such manner?

Reason behind this…

So I took a look at the Processes tab in the Task Manager and noticed that “Microsoft Compatibility Telemetry” process was hogging up the Disk usage, which is apparently the process that comes built into Windows 10 to collect and send our Usage Data to Microsoft.

And believe me this process was dominating the whole Read and Write usage of the Disk, that it was spiked up to over 90% disk usage only for this process. 😮

Now I don’t have any problem with Microsoft collecting my personal usage data for the reason of “improving their product” (which is what they say at least), but if it’s disturbing my day to day work, then you’re crossing a line! lol

So I killed the above process and re-ran my build,

BOOM! IT WORKED! 😀

And then another time the same issue occurred, I took a look at the Task Manager and noticed that my Anti-Virus which is “Kaspersky was running a scheduled Rootkit Scan” and it was hogging up the Disk usage over 90%!

So I cancelled the scan process and re-ran my build,

BOOM! IT WORKED! 😀

So now you know….

So as of my above experience you can clearly see that those build errors occur due to

excessive usage of Disk’s Read and Write by other Processes…

and it’s somehow disturbing the Build process for obvious reasons.

Now I’m not saying the above errors occur only for this specific reason, but in case if you couldn’t find a reason, then you may have to look into this aspect as I did! 😉

There you have it, I just shared my experience with yol, hope it may help someone!

Cheers! Stay awesome Devs!

😀

Udara Alwis OUT!

Wait… How could I handle Click event of a Custom Renderer Button in Xamarin Forms ? :|

Now we all know how Xamarin allows your to override the renderering process of any given UI control from native level and do any sort of modifications through Custom Renderers.

Completely overriding Xamarin Forms Control in Custom Renderer?

It even allows you to completely override the whole Control that’s associated with Xamarin Forms type Control and replace it with a completely native type Control. Specifically in cases like where you override the Control property with SetNativeControl() method in your Custom Renderer.

But when you do that…

But what happens when you complete replace and override the associated default control for your renderer is that, you will lose the access to Events of that particular control.

To be specific…

Let’s take a look at the following Custom Renderer…

[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class CustomButtonRenderer : ButtonRenderer
    {
        protected override async void OnElementChanged(ElementChangedEventArgs<CustomButton> e)
        {
            base.OnElementChanged(e);
            
            if (e.NewElement != null)
            {
		Android.Widget.Button nativeButton = new Android.Widget.Button();
			
                SetNativeControl(nativeButton);
            }
        }
     }
}

 

There you can see we are completely replacing the default Button Control associated with the Renderer with our own native Button control.

When you do that, since you’re completely replacing everything, you will lose access to all the events and properties associated with the default control. Such as Button Click, Touch Events and so on.

As in try to subscribe to your CustomButton’s default Clicked event, it won’t fire up during run time, since it been overridden by the native button control.

So how to handle events?

Yep in that case, we need to handle those events manually and map those necessary events from our Native button control to Xamarin Forms level properties and events.

Custom Events…

Yep this is how you manually create an Event for your Custom Button.

public class CustomButton : Button
{
	public event EventHandler ClickedCustom;
	
	public void SendCustomClicked()
	{
		EventHandler eventHandler = this.ClickedCustom;
		eventHandler?.Invoke((object)this, EventArgs.Empty);
	}
}

 

And then upon the Native Button’s Click event we invoke this event from the Custom Renderer level. 🙂

nativeButton.ClickEvent += (sender, args) =>{
	view.SendCustomClicked();
}

 

And then at the run time it will fire up the ClickedCustom event for your Custom Button in response of the native button’s click.

So now you can subscribe to ClickedCustom event instead of default Clicked event in your Xamarin Forms code and get the response upon the custom button click.

Any other type of events and properties…

You could follow the same pattern for any other type of event you wish to handle, and even properties such as Text, Color and blah blah… 😉

TADAAA! 😀

Enjoy!

Let’s Solve, Error inflating class android.support. v7.widget.Toolbar …

So the other day I created a new Xamarin Forms solution in Visual Studio for one of my sample apps, and tried to build and run it.

Something to keep a note here my

  • VS – Xamarin Version – 4.2.2.1
  • VS – Xamarin Android Version – 7.0.2.42
  •  Xamarin Forms Version – 2.3.3.180

Build and Run, worked perfectly on iOS.

but on Android?

Then I tried running the Android app, and suddenly at runtime, KABOOM!

Error inflating class android.support. v7.widget.Toolbar…

Without even any build errors, a fresh out of the box project in Visual Studio!

It seemed like some Android dlls were missing in the runtime, something to do with Toolbar. 😮

This didn’t make any sense because I haven’t done any modifications to the project or even written any single line of code in the project, this was just a fresh out of the box Xamarin Forms solution.

So as usual I tried Clean & Rebuild, Restart VS, Restart the PC and so on many other random stuff. But still couldn’t figure out.

A WEIRD SOLUTION!

So as of a final destination I tried downgrading the Xamarin Forms version in the solution, and BOOM! IT WORKED!

So I thought may be this was a bug in the Xamarin Forms version I was using, but just to clarify it I upgraded the Xamarin Forms version back to the original version.

and BOOM! IT WORKED! 😀

screen-shot-2017-02-06-at-9-42-04-pm-2

Right Click on the Solution -> Manage Nugest Packages -> Select Xamarin.Forms package -> Tick on all the Projects in your Solution -> go to the Version selector -> select a lower  Xamarin.Forms version and click Install -> restart VS -> Clean & Rebuild

Then do the same process but when you’re selecting the Xamarin.Forms version, make sure to select the one you had originally at first place when you created your solution! 😉

Probably…

Although this doesn’t really make any sense why it would throw such a runtime error, fresh out of the box, and then magically fixes after downgrading and upgrading back the Xamarin Forms version in the solution, but I’m guessing its something to do with the Xamarin Extension for Visual Studio, which might be messing up with adding some Android dependencies to the solution.

Anyways, I just posted this in any case if you ever came across such a situation yourself! 😀

Cheers! 😀

Is it possible to add a Text Shadow in Button with Xamarin Forms ? ;)

Let’s face it, sometimes your UX Lead comes up with crazy screen designs, and its us developers who has to go through the pain of delivering the design implementation accordingly. Yeah one of those moments I went through was when I had given a task to implement a Button Control with Text Shadow effect in Xamarin Forms

More descriptively, create a button which has a shadow effect underneath its internal Text?

Yeah some of your wonder why would someone even pay attention to such tiny details, yeah well you know UX fellows. 😉 lol

1

Well anyways you can’t really deny the text shadow does add some beauty to the button as you can see from above! 😉

Is this possible?

Anyhow, this is not possible in Xamarin Forms default Button, oh well you can’t even set an Image for the button’s background in Xamarin Forms unfortunately.

So the solution?

Well as usual we shall be praising Custom Renderers for our rescue. 😀 Hence such effects are available by default in Android and iOS Button controls.

So for you Github-errrs you may grab my code up in here: Xamarin-Playground/XFTextShadowButtonControl

First subclass our Custom Button…

Let’s create our TextShadowButton control by subclassing the Xamarin Forms Button control. Also you need to add a property to set the Shadow Color in this awesome button control. 😀

namespace WhateverYourNamespace
{
    public class TextShadowButton : Button
    {
		public static readonly BindableProperty TextShadowColorProperty =
        BindableProperty.Create(
        nameof(TextShadowColor),
        typeof(Color),
        typeof(TextShadowButton),
        Color.Gray);

        /// <summary>
        /// Gets or Sets TextShadowColor property
        /// </summary>
        public Color TextShadowColor
        {
	        get
	        {
		        return (Color)GetValue(TextShadowColorProperty);
	        }
	        set
	        {
		        SetValue(TextShadowColorProperty, value);
	        }
        }
    }
}

 

There you go, and let’s set the default Shadow color as Gray. 😉

So iOS stuff?

Next time for the Custom Renderer for this control in iOS..

[assembly: ExportRenderer(typeof(TextShadowButton), typeof(TextShadowButtonRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class TextShadowButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            var view = (TextShadowButton) Element;
            if (view == null) return;
            
            // Adding the Button text shadow effect
            Control.TitleLabel.ShadowOffset = new CGSize(0, 0.25);
            Control.SetTitleShadowColor(((TextShadowButton)Element).TextShadowColor.ToUIColor(), UIControlState.Normal);
        }
    }
}

 

The native iOS Control that associates with Xamarin Forms Button is UIButton, which has the properties called, TitleLabel.ShadowOffset and TitleShadowColor that you could use to add the Shadow effect to our Button Text 😉

then Android stuff?

Next is the Android Renderer for our TextShadowButton

[assembly: ExportRenderer(typeof(TextShadowButton), typeof(TextShadowButtonRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class TextShadowButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);

            var view = (TextShadowButton)Element;
            if (view == null) return;

            // Adding the Button text shadow effect
            Control.SetShadowLayer(4, 0, 2, ((TextShadowButton)Element).TextShadowColor.ToAndroid());
        }
    }
}

 

So in native Android Button, we have the ShadowLayer property which we could use to simulate a shadow effect on the Button Text. There we have set the shadow radius and pointed the shadow view lower than the text view by setting the Y axis to value 2.

time for Consumption of this sweetness! 😉

Alright, add this sweetness into your page and take a look…

<StackLayout>
	<Button Text="This is normal Button" BackgroundColor="#f8c220" TextColor="White"/>
	<local:TextShadowButton Text="Awesome Button with Shadow" BackgroundColor="#f8c220" HeightRequest="37" TextColor="White"/>
</StackLayout>

 

So what are you waiting for? Hit F5 and Run! 😀

2

screen-shot-2017-02-06-at-8-59-25-pm  nexus-5-lollipop-screenshot-2

WOOT! WOOT! 😀

Share the beauty! 😉 Cheers!

Awesome Xamarin Forms Label with HTML Text Formatting…

Why would you wanna use a WebView when you could use your Label to display HTML mark up text in your Xamarin Forms app? 😉

How it all started?

Well some times back I had to implement a Xamarin Forms Label which can display HTML formatted text…

The problem with Xamarin Forms Label?

Well of course you would tell me to use the FormattedText property built into Xamarin Forms Label. But before you say that do you even know how limited that property is? and you have to break up your string in to pieces and rebuild it with Span blocks, and also there’s only a few text formatting options available. Usually HTML has a ton of text formatting options, which you can even get close to with the default Xamarin Forms Span block customization.

So the default Xamarin Forms Label can not do any help at this case.

Solution?

Well we all know it’s super easy to parse HTML text to be rendererd in a Label with Android and iOS native implementation. That’s why I had to drill down to native level and come up with a Custom Label that could display HTML markup text. 😀

Without further due, let’s jump into it! 😉

Create the Custom Control…

So as usual let’s create our Custom Label by subclassing Xamarin Forms Label control.

namespace WhateverYourNamespace
{
    public class HtmlFormattedLabel : Label
    {

    }
}

 

Nothing fancy there… Next are the big stuff!

Xamarin Android implementation…

So here’s the renderer for our HtmlFormattedLabel

[assembly:ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class HtmlFormattedLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (HtmlFormattedLabel)Element;
            if (view == null) return;
            
            Control.SetText(Html.FromHtml(view.Text.ToString()),TextView.BufferType.Spannable);
        }
    }
}

 

So what we basically do here is native Android TextView through the Control property of our renderer and access the SetText() method, and  directly use the Android HTML parser to set your HTML Text.

Xamarin iOS implementation…

Next is our iOS renderer for the custom control.

[assembly:ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class HtmlFormattedLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            
            var view = (HtmlFormattedLabel)Element;
            if (view == null) return;

            var attr = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();
            attr.DocumentType = NSDocumentType.HTML;
            
            Control.AttributedText = new NSAttributedString(view.Text, attr, ref nsError);
        }
    }
}

 

So here what we do is, we access the native iOS UILabel through the Control property and directly set the AttributedText property with our natively parsed HTML string. 😉

Now unlike Android, I wasn’t much familiar with iOS implementation of HTML text parsing, therefore I took some help from this thread for the above implementation How to display html formatted text in a UILabel ?.

KABOOM! EASY!

Let’s consume this Awesome Label! 😉

Alright time to use the Awesome Label we just created in Xamarin Forms!

Content = new StackLayout
{
	VerticalOptions = LayoutOptions.Center,
	Padding = new Thickness(20,0,20,0),
	Spacing = 30,
	Children = {
		new Label {
			HorizontalTextAlignment = TextAlignment.Center,
			TextColor = Color.Black,
			Text = "Welcome to the awesome HTML Formatter Label" +
			"Control by ÇøŋfuzëÐ SøurcëÇødë!"
		},
		new HtmlFormattedLabel()
		{
			FontSize = 14,
			TextColor = Color.Black,
			Text = 
			   "<html><body><Center>" +
			   "<font size='6'>" +
			   "This is a html formatted text," +
			   "so this is <b>bold text</b>... " +
			   "and this is <u>underline text</u>... " +
			   "and this is <strike>strike through text</strike>... " +
			   "and finally this is <i>italic text</i>... " +
			   "<br />" +
			   "Ops this is html line break..." +
			   "<br />" +
			   "And this is <sup>superscripted</sup> html text."+
			   "</font>" +
			   "<Center></body></html>",
		}
	}
}

 

So here I’m using our HtmlFormattedLabel control and directly setting a HTML formatted text to its Text property. 😀

Now hit F5 and Run that beautiful code! 😉

screen-shot-2017-02-05-at-4-08-31-pmnexus-5-lollipop-screenshot-3

There you have it fellas! 😀

Now you may grab this code from my github: Xamarin-Playground/XFHtmlFormattedLabelControl

Enjoy!

And pass on to another Developer by sharing it! 😉

I encountered “GenerateJavaStubs” task failed unexpectedly in Xamarin Android

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

What happened ?

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

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

Solution ?

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

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

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

TADAAA! 😀

Xamarin Android deployment error INSTALL_FAILED_ UPDATE_INCOMPATIBLE

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

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

or with a similar error code as below?

[INSTALL_FAILED_DUPLICATE_PERMISSION]

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

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

As the solution?

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

adb uninstall my.package.id

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

And try again! Should be good to go! 😉

Animate a CATextLayer in Xamarin iOS

So this is a flash post about animating CATextLayer text color, or in descriptively animating ForegroundColor property of CATextLayer. 🙂 With Xamarin iOS!

Since this is a flash post I’m not going to explain what is CALayers or Core Animations of Xamarin iOS, rather let’s just jump into the code.

Using CABasicAnimation

Here’s the code…

// animate text color with CABasicAnimation
CABasicAnimation myCAbasicAnimation = CABasicAnimation.FromKeyPath("foregroundColor");
myCAbasicAnimation.SetFrom(UIColor.Blue.CGColor);
myCAbasicAnimation.SetTo(UIColor.Purple.CGColor);
myCAbasicAnimation.FillMode = CAFillMode.Forwards;
myCAbasicAnimation.Duration = 1.0f;
myCAbasicAnimation.RemovedOnCompletion = false;

// Add the animation to your CATextLayer
_myCAtextLayer.AddAnimation(myCAbasicAnimation, null);

 

So we basically set the FromKeyPath value which is the key value string for the property you want to target in your CATextLayer, in this case the “foregroundColor” as in the Text color.

Then we set the SetFrom and SetTo values, respectively the values to be animated in between. 🙂

Then if you want to remove this animation from your CATextLater upon completion, you could set the RemovedOnCompletion property to be true. Finally add the animation to your CATextLater by calling AddAnimation() and pass in the CABasicAnimation we just created. 😀

If you want to repeat and even reverse this animation, or put it in a loop, then use the below properties. 😉

myCAbasicAnimation.AutoReverses = true;
myCAbasicAnimation.RepeatCount = Single.PositiveInfinity;

 

TADAAAA! 😀

Using CATransaction

Here’s the code…

// animate text color with CATransaction
CATransaction.Begin();
// you could set CATransaction values by the key
CATransaction.SetValueForKey(new NSNumber(1.0f), CATransaction.AnimationDurationKey);
// or you could directly use properties AnimationDuration
//CATransaction.AnimationDuration = 1.0f;
_myCAtextLayer.ForegroundColor = UIColor.Purple.CGColor;
CATransaction.Commit();

 

This rather is rather good for animating a whole group of layers or animatable properties at the same time as an animation block. CATransactions are explicit where as you begin the modification layer upon Begin() call and finishes up on Commit() call.

That’s it. 😉

I guess in future I would be posting more of these “Flash Posts”, instead of lengthy explanatory articles due to work stuff. 😦 Hope for the best! 😀