CodeMash 2020 This Week!

This week I’ll be at CodeMash – an amazing developer event at the Kalahari Resort in Ohio. CodeMash holds a special place in my heart; It’s the first developer conference I ever attended, the first I ever sponsored, and now I have the honor of being a speaker!

This year, I’ll be talking more about Kotlin for C# developers, and you can catch the session at 9:15 am on Thursday.

Annotation 2020-01-06 113339

If you’re looking to expand your language portfolio with something familiar yet new as a C# developer, you’re going to love this session. Learn about the Kotlin programming language side-by-side with C#, compare and contrast both languages’ amazing features and tooling and walk away with the confidence to to explore and build more with both languages and stacks.

Check out the schedule and other speakers here: https://www.codemash.org/

If you’re at the conference or the area, let me know! I’d love to chat.


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Techorama This Week – Kotlin, C#, Flux, Design Patterns, and more!

If you’re in the Netherlands this week, come catch me at Techorama! I’ll be there from the 30th through the 3rd of October and presenting two different sessions:

techorama_sessions

On the 1st, I’ll be speaking on Kotlin for C# Developers:

Dive into the latest craze in languages and platforms – Kotlin. This time we will be looking at it from the perspective of a .NET C# developer, draw comparisons between the languages, and bridge the gap between these 2 amazing languages. We’ll look at: – Kotlin as a language – Platforms Kotlin is great for – Object Oriented Implementations in Kotlin – Extended Features – Features Kotlin has that C# doesn’t – A demo Android application in Kotlin vs a Xamarin.Android app in C# In the end you will leave with a foundational knowledge of Kotlin and its capabilities to build awesome apps with less code. You should feel comfortable comparing C# applications to Kotlin applications and know where to find resources to learn even more!
And on the 2nd I have another morning session on implementing the Flux design pattern in C# and .NET:
Learn about the Flux design pattern and how to implement it in your C# client applications like UWP, Xamarin, and all the other platforms .NET is touching now. We’ll compare Flux and Uni-Directional data flows to the existing tools and directions development takes us in C# client apps and talk about all the pros and cons that come with both. We’ll take an existing Xamarin.Forms app using MVVM and “Flux it Up” to migrate to a more 1-direction flow of data and actions. When you leave, you’ll have a solid understanding of Flux and some of its existing implementations such as Redux and be confident in implementing it yourself in C#!

Pre-conference Meetup

If you’re not going to Techorama this year, but are still in the area, you can find me tomorrow at the Dutch Mobile .NET Developers meetup with some of the other amazing people from the Xamarin and .NET Community. I’ll be on a panel talking about mobile technologies and practices!

https://www.meetup.com/Dutch-Mobile-NET-Developers-Group/events/262894590/

 

Here’s the schedule:

18:00 Doors open & Dinner
19:00 – 20:00 The Latest and Craziest for Mobile .NET Developers
David Ortinau @davidortinau
Microsoft has been hard at work improving Visual Studio and Xamarin for mobile developers. I’ll demo the latest features you can use to make your dev experience better today. And in the future? Microsoft has some “coming soon” as well as highly experimental projects that are “must see”!

20:00 – 20:15 Break
20:15 – 21:00 Mobile Expert Panel with Alex, Brandon, Dan & Gerald
Open Q&A for these mobile experts that have absolutely made their mark in the mobile developer space. This is your chance to ask anything you’d like! Joining us are:

Alex Dunn @suave_pirate
Author at Pluralsight | Xamarin MVP | Microsoft MVP

Brandon Minnick @thecodetraveler
Microsoft Developer Advocate | Mobile App Developer

Dan Siegel @danjsiegel
Microsoft MVP | @PrismLib Maintainer | Xamarin Evangelist | @XamDevSummit Organizer

Gerald Versluis @jfversluis
Engineer @Microsoft for #XamarinForms | Former Microsoft MVP

21:00 Drinks & Closing

 

See ya’ll there!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

New Pluralsight Android Skill IQ Tests

I recently worked with Pluralsight (pluralsight.com) to help produce 2 brand spankin’ new Skill IQ Tests! Test your skills and knowledge of Android development, Android Studio, Kotlin and more!

Android Tooling Skill Assessment

The first is Android Tooling! You can test your knowledge of:

  • Android Studio – Analyze
  • Android Studio – Basics
  • Android Studio – Build
  • Android Studio – Code Manipulation
  • Android Studio – File Structure
  • Android Studio – Run
  • Android Studio – Settings
  • Android Studio – Tools
  • Android Studio – Version Control
  • Gradle

Although this exam is still in Beta (as of writing this post), you can still take the exam and I encourage you to as well! Pluralsight does some really cool work to calibrate the curve of the skill assessment so give it a go and let me know how you do 🙂

Take it here: https://app.pluralsight.com/score/skill-assessment/android-tooling/intro#/v2/landing 


Kotlin: Enhancing App Experience

The second skill assessment is for you Kotlin lovers like me and dives into some deeper knowledge of building better Android apps with Kotlin!

Kotlin is an open-source JVM language created by JetBrains. It is one of the most popular languages used in Android development.

The assessment may cover:

  • Activities
  • Enhanced System Integration
  • Threading and Background Work
  • User Interface and Experience

This assessment is also still in Beta, but be sure to try this one out and see if your Kotlin skills are up to snuff.

Check Out My Course!

Oh wow how topical and convenient! Be sure to check out my course on Building Android Apps with Kotlin: Getting Started to learn a lot about the fundamentals of both the Kotlin language and Android development as a whole! I assure it will help drive that Skill IQ Up for both of these assessments 🙂 

https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started 

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Build Your Own In-App Developer Options

This post is a continuation of building gesture based “easter eggs” into your Xamarin apps (native or Forms).

In this post, we are going to continue from these posts:
Xamarin.Tip – Add Easter Eggs to UWP with Key Combos
Xamarin.Tip – Add Easter Eggs on Shake

to talk about how we can use these gestures in Debug mode to give ourselves some shortcuts for testing and moving through our application quicker.

To breakdown the process setup – we added shake handlers (and keyboard shortcuts for UWP) that can invoke any contextual code in our application. We talked about using this for funny easter eggs, but this functionality can be made into something super useful for us.

I call this “Contextual Developer Options”. The idea is take that easter egg handler and use it to display some contextual options that can be controlled page by page or view by view. This can be toggling some UI updates, auto-navigating through the app, testing different scenarios, etc.

In this example we’ll be using MVVM and Xamarin.Forms to demonstrate the possibilities, but the same idea can be applied to any other pattern or practice. Basically we need to:

  • Register dev options to whatever context we want
  • Determine what context we are in
  • Display the actionable dev options

Before starting, I suggest looking at something like Allan Ritchie’s incredibly useful UserDialogs package https://github.com/aritchie/userdialogs

We’ll use it in our examples.

Setting Up Developer Options

First things first, let’s define our developer options.

DevelopmentOption.cs

public class DevelopmentOption
{
    public string Title { get; set; }
    public Action Action { get; set; }
}

Now, like I said, our example will be doing this in MVVM and we can use the current page the user is on as the context we want to apply.

I’ll start by creating a BasePageViewModel that we can use to set up our developer options and execute the action

BasePageViewModel.cs

public abstract class BasePageViewModel : ViewModelBase
{
    protected List<DevelopmentOption> _developerOptions;
    private bool _isShowingDeveloperOptions = false;

    public BasePageViewModel()
    {
        _developerOptions = new List<DevelopmentOptions>();
    }

    /// <summary>
    /// Shows the developer options. This should be called after a native easter egg such as a shake.
    /// </summary>
    public virtual async Task ShowDeveloperOptionsAsync()
    {
        if (_developerOptions.Any() && !_isShowingDeveloperOptions)
        {
            var titles = _developerOptions.Select(d => d.Title);
            _isShowingDeveloperOptions = true;
            var actionResult = await UserDialogs.Instance.ActionSheetAsync("Developer Options", "Cancel", null, null, titles.ToArray());
            _isShowingDeveloperOptions = false;
            // see if an option was selected
            if (titles.Contains(actionResult))
            {
                // call it if we find it.
                var option = _developerOptions.FirstOrDefault(d => d.Title == actionResult);
                option?.Action();
            }
        }
    }

    /// <summary>
    /// Sets up the developer options.
    /// </summary>
    protected virtual void SetupDeveloperOptions()
    {
        _developerOptions.Add(new DevelopmentOption()
        {
            Title = "Go to debug page",
            Action = () => UserDialogs.Instance.Toast("Not implemented")
        });
    }

    /// <summary>
    /// Adds the developer option.
    /// </summary>
    /// <param name="title">Title.</param>
    /// <param name="action">Action to perform when selected.</param>
    protected void AddDeveloperOption(string title, Action action)
    {
        _developerOptions.Add(new DevelopmentOption()
        {
            Title = title,
            Action = action
        });
    }
}

Alright let’s breakdown what’s going on here.

Our BasePageViewModel has a List that represents our different options for the given page. Then we have some protected methods we can use in our extended PageViewModels to setup different options.

In our SetupDeveloperOptions method, we can setup any option we want for the page, and we put a universal “Go to debug page” example action that is there on every page.

So here’s an example of a useful ViewModel that sets up a login page developer option.

LoginPageViewModel.cs

public class LoginPageViewModel : BasePageViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
    protected override void SetupDeveloperOptions()
    {
        AddDeveloperOption("Use test user", () => 
        {
            Email = "mytestuser@mydomain.com";
            Password = "myP@ssw0rd";
        });
    }
}

So what we want on this login page is to be able to shake the device and see the Action Sheet that shows “Use test user” and when selected, it should fill out the fields on the page automatically.

Now that our setup is done, let’s wire up accessing these developer options.

Wiring It Up

We need to be able to access our Page’s ViewModel in order to execute the developer options when the shake happens. To do this, we can access the current page via the Xamarin.Forms.Application.Current static accessor. Then use the MainPage property to get around.

I like to add a simple helper property getter on my App class for this:

App.xaml.cs

public class App : Application
{
    // ...

    // assuming MainPage is a NavigationPage. You can do some extra logic if it isn't
    public ContentPage CurrentPage => (MainPage as NavigationPage)?.Navigation?.NavigationStack?.Last()
    // ...
}

Now in our native app logic, where we were executing the easter egg we can call:

// we don't want developer options in production 🙂
#if DEBUG
await ((App.Current as App)?.CurrentPage?.BindingContext as BasePageViewModel)?.ShowDeveloperOptionsAsync();
#endif

So now if we are in our LoginPage and our BindingContext is set to our LoginPageViewModel, our shake should reveal the action sheet!

Conclusion

We can make our lives a whole lot easier when testing and running through our app by giving ourselves easier and contextual options throughout the entire application.

I’ve personally used this for some pretty awesome and intense stuff like:

  • Filling out forms with different values
  • Changing styles/themes of the app to easily compare 2 different UIs
  • Test different states of a page such as if a user is logged in or not
  • Test error scenarios
  • Build a page that shows logs of all interactions and background tasks in the app and use the developer options to navigate to that page whenever to see those custom logs live (even when not attached to the debugger)
  • Execute custom native code to make debugging easier
  • Navigate quickly to the page deep in the app I am currently working on

Remember to still write unit and UI tests for your app too! This is meant to be something to make real hands-on testing even easier too.

It has saved me hundreds of hours easily. Let me know if you end up implementing something like this too!

For now, I don’t have any complete open source project to demo this, but if enough of you want to see a full example and screenshots and different scenarios, I’ll consider putting a full project together. Let me know in the comments or on twitter!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Adding a Password Toggle Button in iOS

In a previous post, we looked at how easy it was to add a Password Toggle button in our Xamarin.Android apps (or native Android since it was only in the xml layout): Xamarin.Tip – Adding a Password Toggle Button in Android

So in this post, let’s work toward a similar behavior in our Xamarin Native iOS!

The basic premise is to extend the UITextField control and add a SubView to it for the button. Then on this UIButton.TouchUpInside, we want to toggle the UITextField.SecureTextEntry boolean property.

With that in mind, there are a number of ways we can do this!

  • Create a custom PasswordToggleTextField and design it in a xib to drag and drop the button
  • Add the UIButton at runtime everywhere we want to use it
  • My Favorite: Use NativeBehaviors and create a reusable behavior that can be attached to any given UITextField.

Let’s continue down this path with the NativeBehaviors approach. Of course, if you don’t want to do it this way, you can simply copy the code within the Behavior we create and apply it anywhere else.

NativeBehaviors is a package I created just a little while back that brings the Xamarin.Forms style Behavior pattern to native iOS, Android, and UWP controls. So if you’ve written Xamarin.Forms Behaviors before, this should be super familiar!

Let’s do this by creating a simple TextFieldTogglePasswordBehavior.

TextFieldTogglePasswordBehavior.cs

/// <summary>
/// Text field toggle password behavior.
/// </summary>
public class TextFieldTogglePasswordBehavior : NativeBehavior<UITextField>
{
    public override string BehaviorName => nameof(TextFieldTogglePasswordBehavior);

    private UIButton _togglePasswordButton;

    /// <summary>
    /// Attach show/hide button
    /// </summary>
    /// <param name="bindable">Bindable.</param>
    protected override void OnAttachedTo(UITextField bindable)
    {
        _togglePasswordButton = new UIButton()
        {
            Frame = new CGRect(0, 0, 50, 8)
        };

        _togglePasswordButton.SetTitle(bindable.SecureTextEntry ? "Show" : "Hide", UIControlState.Normal);
        _togglePasswordButton.SetTitleColor(UIColor.White, UIControlState.Normal);
        _togglePasswordButton.SetAttributedTitle(new Foundation.NSAttributedString(bindable.SecureTextEntry ? "Show" : "Hide", UIFont.SystemFontOfSize(12)), UIControlState.Normal);
        _togglePasswordButton.TouchUpInside += (sender, e) =>
        {
            var updatedIsPassword = !bindable.SecureTextEntry;
            bindable.SecureTextEntry = updatedIsPassword;
            _togglePasswordButton.SetTitle(updatedIsPassword ? "Show" : "Hide", UIControlState.Normal);
            _togglePasswordButton.SetAttributedTitle(new Foundation.NSAttributedString(updatedIsPassword ? "Show" : "Hide", UIFont.SystemFontOfSize(12)), UIControlState.Normal);
        };
        _togglePasswordButton.TitleLabel.TextColor = UIColor.White;
        bindable.RightViewMode = UITextFieldViewMode.Always;
        bindable.RightView = _togglePasswordButton;
        bindable.RightViewRect(new CGRect(0,0, 50,8));
    }

    /// <summary>
    /// Kill the button
    /// </summary>
    /// <param name="bindable">Bindable.</param>
    protected override void OnDetachingFrom(UITextField bindable)
    {
        _togglePasswordButton = null;
        bindable.RightView = null;
    }
}

If you read through the code a bit, you noticed that we simply create a UIButton, set its text to UIColor.White, and then update the text of the button to either “Show” or “Hide” depending on the state, and then in the TouchUpInside handler, we update that state as well as the SecureTextEntry property of the parent UITextField this behavior gets attached to!

You can also update this to use icons instead of regular text buttons to get a behavior closer to the Android treatment if you wanted. It’s just a button, so go crazy.

Now let’s take this behavior and attach it to an existing UITextField control that we have added to a UIViewController in our Storyboard.

In this example, I’m using a custom UITextField called MaterialTextField to show that this behavior is usable on the built in controls as well as any other custom UITextField:

LoginViewController.cs

public class LoginViewController : UIViewController 
{
    // note: this is now reusable if you want to apply the behavior to multiple fields
    // without creating a bunch of new instances.
    private readonly TextFieldTogglePasswordBehavior _togglePasswordBehavior = new TextFieldTogglePasswordBehavior();

    protected void ViewDidLoad() 
    {
        PasswordTextField.AttachBehavior(_togglePasswordBehavior);
    }
}

And that’s it! If we want to remove the button and detach the behavior, all we have to do is call:

PasswordTextField.DetachBehavior(_togglePasswordBehavior);

With all that together, we get a pretty neat control!

Screen Shot 2018-03-15 at 11.04.00 AMScreen Shot 2018-03-15 at 11.03.54 AM

In a future post, we can look at how to achieve this same concept in Xamarin.Forms – without using custom renderers!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Embed Your Xamarin.Forms Pages in Your iOS ViewControllers

The number one complaint I hear about Xamarin.Forms is the slow startup time of the applications that use it. The team at Xamarin has done a lot to help with this and give some more options such as XAML Compilation, Lazy Loading, and Ahead of Time Compilation. Check out some of David Ortinau’s suggestions here: 5 Ways to Boost Xamarin.Forms App Startup Time.

However, one of the best ways I’ve found to help with this issue is to use Xamarin.Forms Embedding to its full potential. Embedding became available in Xamarin.Forms 2.5 and at a high level allows you to embed your Xamarin.Forms pages into your Native Xamarin views by using the extension methods .CreateFragment(Context context); for Android and .CreateViewController(); for iOS. This is most commonly used for when you want to share some UI in your Xamarin Native apps using Xamarin.Forms, however you still need to call Xamarin.Forms.Init() which is one of the main culprits in the slow startup time.

For Android embedding, see: Xamarin.Tip – Embed Your Xamarin.Forms Pages in Your Android Activities

iOS

The solution proposed here still allows you to create almost all of your views in Xamarin.Forms by using embedding, but requires some architecture and design changes. The premise is this:

  • First ViewController is non-Xamarin.Forms and loads your app right away
  • Init Xamarin.Forms after this ViewController is loaded
  • Embed Xamarin.Forms pages in other ViewControllers
  • Lift navigation out of Xamarin.Forms and into the native navigation.

This also has advantages outside the startup time such as better performance on transitions, more natural look and feel to end-users, performance gains in other areas, and a smaller app-size.

This means:

  • No NavigationPage
  • No Xamarin.Forms toolbar (using the native UINavigationBar control instead)
  • Still have MVVM and all our bindings we would expect

So if you’re already using a framework that is not tied down to Xamarin.Forms such as MvvmLight, you don’t have to change much behind the scenes since the INavigationService is abstracted.

Let’s kick this off by creating an inheritable ViewController that handles the embedding and layout how we want. Be sure to use your Storyboard and have the RootViewController be a UINavigationController, then use this embeddable ViewController within that.

XamarinFormsViewController

/// <summary>
/// Base xamarin forms view controller. Used for embedding a Xamarin.Forms page within a native view controller.
/// When inheriting from this, be sure to create a ViewController within the storyboard as well so that navigation
/// can properly work.
/// </summary>
public abstract class XamarinFormsViewController<TPage> : UIViewController
    where TPage : ContentPage, new()
{
    protected TPage _page;


    public XamarinFormsViewController(IntPtr handle) : base(handle)
    {
    }

    /// <summary>
    /// Load the Xamarin.Forms Page's ViewController into the parent
    /// </summary>
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        _page = new TPage();
        var xamarinFormsController = _page.CreateViewController();
        AddChildViewController(xamarinFormsController);
        View.AddSubview(xamarinFormsController.View);
        xamarinFormsController.DidMoveToParentViewController(this);

        // add whatever other settings you want - ex:
        EdgesForExtendedLayout = UIKit.UIRectEdge.None;
        ExtendedLayoutIncludesOpaqueBars = false;
        AutomaticallyAdjustsScrollViewInsets = false;

    }
}

When creating a child of this XamarinFormsViewController, be sure to also create an empty ViewController in your .storyboard file for each unique type. This is required for handling navigation using the storyboard and root UINavigationViewController. If you’re using .xib files for some reason, then don’t worry about it, just instantiate the XamarinFormsViewController itself (you’ll have to add the other constructor overloads though).

So now we can create a simple Xamarin.Forms page:

SomePage.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"     x:Class="MyApp.Pages.SomePage">
    <ContentPage.Content>
        <Grid>
            <Label Text="I'm Embedded!" HorizontalOptions="Center" VerticalOptions="Center"/>
        </Grid>
    </ContentPage.Content>
</ContentPage>

Then create the associated ViewController:

SomeViewController.cs

public class SomeViewController: XamarinFormsViewController<SomePage>
{
    protected void ViewDidLoad()
    {
        base.ViewDidLoad();

        NavigationItem.Title = "Some title";
    }
}

Now all we have to do is kick off this SomeViewController after calling Xamarin.Forms.Init() and we are good to go! If we have a MainController we can call it before navigating if it isn’t initialized, or execute it in ViewDidLoad or a similar lifecycle event.

MainController.cs

public class MainController: UIViewController
{    

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

        // assume SomeButton is created and named in the Storyboard file
        SomeButton.TouchUpInside += delegate 
        {
             if(!Xamarin.Forms.Forms.IsInitialized)
                 Xamarin.Forms.Forms.Init(this, savedInstance);

             var someController = this.Storyboard.InstantiateViewController("SomeController") as SomeViewController;
             NavigationController.PushViewController(someController, true);
        }
    } 
}

And there you have it! Some new Xamarin.Forms embedding for performance and other extra benefits 🙂

In future posts of this subject, we’ll look at extending interactions between the Xamarin.Forms Page and the native Activity and ViewControllers, using advanced native components with the embedded Xamarin.Forms Page, and more!

Let me know what you think of this pattern – have you used it? What else would you want to hear about it??

Be sure to checkout some of the Xamarin examples on embedding too!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Adding a Password Toggle Button in Android

Here’s another quick tip to use when building your Android apps whether in Xamarin, or native in Java/Kotlin. Depending on the target audience of your application, you may find it necessary to add a password toggle button to your password EditText to allow users to view and hide their password while typing it.

In this post, we will explore how to do this in Android natively while future posts will cover iOS (which is more involved) as well as building a Xamarin.Forms custom Entry view (no renderer’s required!) to handle the toggling.

There are two places to achieve this in Android – in the xml of the layout resource, or in the code behind where manipulating the view. Luckily, Android (unlike iOS) has this feature built in to the properties of the TextInputLayout control.

We get the ability to show the button as well as apply a custom Drawable if we want!

Using the Layout Resource

Here is an example using the TextInputLayout from the xml side to wrap an EditText:

activity_login.axml

<android.support.design.widget.TextInputLayout
    android:id="@+id/password_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true"
    app:passwordToggleTint="@android:color/white">
    <android.support.design.widget.TextInputEditText
        android:id="@+id/password_editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:password="true"
        android:hint="Password"
        android:textColor="@android:color/white"
        android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>

Notice the two properties:

app:passwordToggleEnabled="true"

and

app:passwordToggleTint="@android:color/white"

These are the two that control showing the password toggle. Alternatively, you can set the

app:passwordToggleDrawable="@drawable/someDrawable"

Using Code

If you’re manipulating your TextInputLayout in your code, you can also update these fields very easily:

LoginActivity.cs

public class LoginActivity : AppCompatActivity
{
    protected override void OnCreate(Bundle savedInstance)
    {
        base.OnCreate(savedInstance);
        SetContentView(Resource.Layout.activity_login);

        var editTextLayout = FindViewById<TextInputLayout>(Resource.Id.password_layout);

        editTextLayout.PasswordVisibilityToggleEnabled = true;
    }
}

That’s it!

Results

Take a look for yourself!

Screen Shot 2018-03-15 at 11.04.31 AM
Screen Shot 2018-03-15 at 11.04.40 AM


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – Embed Your Xamarin.Forms Pages in Your Android Activities

The number one complaint I hear about Xamarin.Forms is the slow startup time of the applications that use it. The team at Xamarin has done a lot to help with this and give some more options such as XAML Compilation, Lazy Loading, and Ahead of Time Compilation. Check out some of David Ortinau’s suggestions here: 5 Ways to Boost Xamarin.Forms App Startup Time.

However, one of the best ways I’ve found to help with this issue is to use Xamarin.Forms Embedding to its full potential. Embedding became available in Xamarin.Forms 2.5 and at a high level allows you to embed your Xamarin.Forms pages into your Native Xamarin views by using the extension methods .CreateFragment(Context context); for Android and .CreateViewController(); for iOS. This is most commonly used for when you want to share some UI in your Xamarin Native apps using Xamarin.Forms, however you still need to call Xamarin.Forms.Init() which is one of the main culprits in the slow startup time.

The solution proposed here still allows you to create almost all of your views in Xamarin.Forms by using embedding, but requires some architecture and design changes. The premise is this:

  • First Activity is non-Xamarin.Forms and loads your app right away
  • Init Xamarin.Forms after this activity is loaded
  • Embed Xamarin.Forms pages in other Activities
  • Lift navigation out of Xamarin.Forms and into the native navigation.

This also has advantages outside the startup time such as better performance on transitions, more natural look and feel to end-users, performance gains in other areas, and a smaller app-size.

This means:

  • No NavigationPage
  • No Xamarin.Forms toolbar (using the native Toolbar control instead)
  • Still have MVVM and all our bindings we would expect

So if you’re already using a framework that is not tied down to Xamarin.Forms such as MvvmLight, you don’t have to change much behind the scenes since the INavigationService is abstracted.

Let’s kick this off by creating an inheritable Activity that handles the embedding and layout how we want.

xamarin_forms_activity.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.design.widget.AppBarLayout     
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:layout_gravity="top"
        app:elevation="0dp">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

This layout gives us the native Android toolbar (with the shadow! Another plus!) and a space for us to embed in this FrameLayout.

Now let’s create the Activity:

XamarinFormsActivity.cs

/// <summary>
/// Base xamarin forms activity.
/// This activity contains a single fragment in the layout and renders the fragment pulled from the Xamarin.Forms page
/// </summary>
public abstract class XamarinFormsActivity<TPage> : AppCompatActivity
    where TPage : ContentPage, new()
{
    protected readonly TPage _page;
    protected int _containerLayoutId = Resource.Layout.activity_fragment_container;
    public Android.Support.V7.Widget.Toolbar Toolbar { get; set; }
    public AppBarLayout AppBar { get; set; }

    public XamarinFormsActivity()
    {
        _page = new TPage();
    }

    /// <summary>
    /// Creates the activity and maps the Xamarin.Forms page to the fragment
    /// </summary>
    /// <param name="savedInstanceState">Saved instance state.</param>
    protected override void OnCreate(Android.OS.Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.xamarin_forms_activity);

        Toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
        if (Toolbar?.Parent != null)
        {
            AppBar = Toolbar?.Parent as AppBarLayout;
            SetSupportActionBar(Toolbar);
        }

        // register the fragment
        var transaction = SupportFragmentManager.BeginTransaction();
        transaction.Add(Resource.Id.fragment_container, _page.CreateSupportFragment(this));
        transaction.Commit();
        SupportActionBar?.SetDisplayHomeAsUpEnabled(true);
        SupportActionBar?.SetDisplayShowHomeEnabled(true);
        Toolbar?.SetBackgroundColor(Android.Graphics.Color.White);
        // everything else from this point should be managed by the Xamarin.Forms page behind the fragment
    }
}

So now we can create a simple Xamarin.Forms page:

SomePage.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"     x:Class="MyApp.Pages.SomePage">
    <ContentPage.Content>
        <Grid>
            <Label Text="I'm Embedded!" HorizontalOptions="Center" VerticalOptions="Center"/>
        </Grid>
    </ContentPage.Content>
</ContentPage>

Then create the associated Activity:

SomeActivity.cs

public class SomeActivity : XamarinFormsActivity<SomePage>
{
    protected override void OnCreate(Bundle savedInstance)
    {
        SupportActionBar.Title = "Some Page";
    }
}

Now all we have to do is kick off this SomeActivity after calling Xamarin.Forms.Init() and we are good to go! If we have a MainActivity we can call it before navigating if it isn’t initialized, or execute it in OnResume or a similar lifecycle event.

MainActivity.cs

public class MainActivity : AppCompatActivity 
{    

    protected override void OnCreate(Bundle savedInstance)
    {
        base.OnCreate(savedInstance);
        SetContentView(Resource.Layout.main_activity);
        var someButton = FindViewBy<Button>(Resource.Id.some_button);
        someButton.Click += delegate 
        {
             if(!Xamarin.Forms.Forms.IsInitialized)
                 Xamarin.Forms.Forms.Init(this, savedInstance);
             StartActivity(typeof(SomeActivity));
        }
    } 
}

And there you have it! Some new Xamarin.Forms embedding for performance and other extra benefits 🙂

In future posts of this subject, we’ll look at the same setup for iOS, extending interactions between the Xamarin.Forms Page and the native Activity and ViewControllers, using advanced native components with the embedded Xamarin.Forms Page, and more!

Let me know what you think of this pattern – have you used it? What else would you want to hear about it??

Be sure to checkout some of the Xamarin examples on embedding too!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Android Kotlin Basics – Lazy Loading Images with Picasso

About This Series

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Find other posts in this series: Android Kotlin Basics

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Lazy Loading Images with Picasso

Loading images from remote sources without help can be a pain in Android development. You need to make the http request against the url, download the bytes of the image, create a Bitmap from those bytes, then render that BitMap in an ImageView. Not only is that tedious, but it also leaves room for tons of errors and especially the dreaded OutOfMemoryException that happens oh so often when trying to render large images in Android.

There are some really great libraries out there for helping face this issue that can also provide some other useful tools such as filtering, extensions, customizing, and more.

In the course we use Picasso which is a library by Square to help lazy load images. Find it here: http://square.github.io/picasso/

Picasso does a great job loading images asynchronously and handles rendering them with proper scale. It does a great job handling this performance in ListViews and RecyclerViews as well. This is exactly how we use it in our real-world app that we build in the course!

Picasso also has some great features with creating custom transformations or extending the functionality. In this post we will stick to the basics though. If you want to get into details check out the Java documentation at their website. Copy and pasting that into a Kotlin file in Android studio will also automatically translate it for you!

Installing

Picasso can be installed 3 ways:
– Gradle (what we use in the course)
– Maven
– Manual

To install with gradle, add:

implementation 'com.squareup.picasso:picasso:2.71828'

to your build.gradle config.

For maven use:

<dependency>
  <groupId>com.squareup.picasso</groupId>
  <artifactId>picasso</artifactId>
  <version>2.71828</version>
</dependency>

And if you want to do it manually, download the jar from http://square.github.io/picasso/ and reference it in your project.

Basic Image Loading

Now that you have Picasso in your project, lets look at how we can do simple image loading.

Let’s start with a simple layout:

activity_main.xml

<RelativeLayout 
    android:layout_height="match_parent"
    android:layout_width="match_parent">
    <ImageView android:id="@+id/myImageView"
        android:layout_height="match_parent"
        android:layout_width="match_parent" />
</RelativeLayout>

Now in our Activity code, we can load the image from the url in the onCreate override.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // load the image with Picasso
        Picasso
            .with(this) // give it the context
            .load("https://i.imgur.com/H981AN7.jpg") // load the image
            .into(myImageView) // select the ImageView to load it into
    }
}

If you’re unsure of why we didn’t need to call

val myImageView = findViewByid<ImageView>(R.id.myImageView)

Check out my post on how Kotlin automatically maps views to properties by id: Android Kotlin Basics – Auto-mapping Views

And that’s it! Now you have automatically handled all performance concerns, caching needs, sizing and downloading, and so much more!

Using in a RecyclerView

So loading a single image into a single ImageView isn’t so bad on its own, but when you have to load high-res images into large lists that can change all the time, there are a lot of places this can go wrong doing it yourself. Developers often run into:
– Lag on new items appearing
– Mismatched images
– No images loading
– Images loading incorrectly
– Dreaded Out of Memory Exceptions

Because Picasso runs the image loading asynchronously and only touches the UI thread when it needs to render the image itself, it avoid the issues of locking the UI up when loading. Because it also caches the images locally, when the image needs to be loaded again (such as scrolling back up), it does so quickly and can void mismatching renderings. Also, because it renders the image in chunks before showing it, they avoid the easy to find Out of Memory Exception that we have all come to hate when trying to render a large image into an ImageView. Normally to avoid this, you have to manually load a scaled down image into memory and handle how you scale it per image. Picasso does all this for us too.

On top of all that, Picasso ships with some of the nice-to-haves such as:
– Transitions when images load or change
– Placeholder images to show while loading from a url
– Transformations on images once loaded
– Debugging indicators to show where the image loaded from

All these great features even scale to these large lists and RecyclerViews.

Before showing how to use it in your RecyclerView, be sure to check out the other post in this series: Android Kotlin Basics – RecyclerView and Adapters unless you’re already familiar with how RecyclerViews and Adapters work 🙂

We can create a layout for our item in our list:

image_item.xml

<ImageView android:id="@+id/myImageView"
    android:layout_height="match_parent"
    android:layout_width="match_parent" />

Then a ViewHolder for this image:

ImageHolder.kt

class ImageHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val myImageView: ImageView = itemView.findViewById<ImageView>(R.id.myImageView)

    fun updateWithUrl(url: String) {
        Picasso.with(itemView.context).load(url).into(myImageView)
    }
}

Now let’s create our Adapter with our datasource:

ImagesAdapter.kt

class ImageAdapter() : RecyclerView.Adapter<ImageHolder>() {
    val imageUrls: Array<string>

    init {
        imageUrls = arrayOf("https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg", "https://i.imgur.com/kUCMPWX.jpg")
    }

    override fun getItemCount(): Int {
        return imageUrls.size;
    }

    override fun onBindViewHolder(holder: ImageHolder?, position: Int) {
        var imageUrl = imageUrls[position]
        holder?.updateWithUrl(imageUrl)
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ImageHolder {
        var imageItem = LayoutInflater.from(parent?.context).inflate(R.layout.image_item, parent, false)
        return ImageHolder(imageItem)
    }
}

Last we just need to create our Activity and wireup the Adapter!

activity_main.xml

<RelativeLayout 
    android:layout_height="match_parent"
    android:layout_width="match_parent">    
    <android.support.v7.widget.RecyclerView
        android:id="@+id/imageRecycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        imageRecycler.layoutManager = LinearLayoutManager(this)
        imageRecycler.adapter = ImageAdapter()
    }
}

Now we can quickly scroll through our list and see the images loaded quickly and properly into our view!

dogs


Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Xamarin.Tip – No Bounce ScrollView in Xamarin.Forms

So on iOS, UIScrollView bounces by default so in Xamarin.Forms the ScrollView natrually bounces. But what if you don’t want your ScrollView to bounce? Android doesn’t bounce, so we won’t worry about it.

Let’s solve this problem with a custom renderer and control called NoBounceScrollView. This could also be done with an Effect but I like to have a custom control with the verbosity and flexibility with a renderer.

Let’s start by building a simple control in our Xamarin.Forms project:

NoBounceScrollView.cs

public class NoBounceScrollView : ScrollView { }

We don’t need anything in it since we are just going to assume it should never bounce and doesn’t affect the ScrollView in any other way. If you want, you can add a bindable property here to set Bouncable or something like that to true or false. Note: if you don’t want your ScrollView to bounce ever, then you don’t need this. Instead just have your renderer replace the default ScrollView renderer.

So we have our Xamarin.Forms control to build the renderer for, so now let’s create the iOS renderer:

NoBounceScrollViewRenderer.cs

public class NoBounceScrollViewRenderer : ScrollViewRenderer
{

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

    private void UpdateScrollView()
    {
        ContentInset = new UIKit.UIEdgeInsets(0, 0, 0, 0);
        if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            ContentInsetAdjustmentBehavior = UIKit.UIScrollViewContentInsetAdjustmentBehavior.Never;
        Bounces = false;
        ScrollIndicatorInsets = new UIKit.UIEdgeInsets(0, 0, 0, 0);
    }
}

What this is doing is setting the content insets to 0 so we don’t have empty space on top or bottom that the bouncing adds, and we also set Bounces to false. Note that the ContentInsetAdjustmentBehavior is only available on iOS 11 and higher, so for that extra step, we need to check the current iOS version.

Lastly, be sure to register your renderer:

[assembly: ExportRenderer(typeof(NoBounceScrollView), typeof(NoBounceScrollViewRenderer))]

or if you are replacing all ScrollViews:

[assembly: ExportRenderer(typeof(ScrollView), typeof(NoBounceScrollViewRenderer))]

Now we have everything we need! So let’s use it in our page:

MainPage.xaml

<ContentPage ...>
    <components:NoBounceScrollView>
        <StackLayout>
            ...
        </StackLayout>
    </components:NoBounceScrollView>
</ContentPage>

Check out the difference!

You can see this control in action with the EF Go Ahead Tours Companion App


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.