CategoryMobile

Creating a circular bitmap in Android in C#

A while ago, I was looking for a way to change a bitmap into a circular bitmap.
There are a lot of good examples on the internet, but none of them completely met my requirements.
So I used one of them as base to create my own helper for creating a circular bitmap.

public static Bitmap CreateRoundedBitmap(Bitmap bitmap, int padding)
{
    Bitmap output = Bitmap.CreateBitmap(bitmap.Width, bitmap.Height, Bitmap.Config.Argb8888);
    var canvas = new Canvas(output);

    var paint = new Paint();
    var rect = new Rect(0, 0, bitmap.Width, bitmap.Height);
    var rectF = new RectF(rect);

    paint.AntiAlias = true;
    canvas.DrawARGB(0, 0, 0, 0);
    canvas.DrawOval(rectF, paint);
    paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));

    canvas.DrawBitmap(bitmap, rect, rect, paint);
    return output;
}

I’m not a fan of static methods, but when no context is used, I’m not that bothered.

A border can be added by drawing a second oval with a stroke width and a color property set to the paint instance.

 var rect2 = new Rect(padding, padding, bitmap.Width - padding, bitmap.Height - padding);
 var p = new Paint();
 p.Color = Color.White;
 p.StrokeWidth = 10;
 p.AntiAlias = true;
 canvas.DrawOval(new RectF(rect2), p);
 

This example creates a white border around the circular bitmap.

In my app, I use a lot of white circular bitmaps. To keep the code as DRY as possible, I created another helper method for creating white bitmaps.

public static Bitmap CreateWhiteBitmap(int width = 160, int height = 160)
{
    var bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
    Canvas c = new Canvas(bitmap);
    c.DrawColor(Color.White);
    c.Save();
    return bitmap;
}

Another static. Still can’t be bothered, because no context is used.
I do like to point out that statics can be very dangerous. When statics are used as repositories to read static variables, files or whatever kind of data, remember to at least always use locks, but even better… just don’t use statics!!

Now let’s bring it all together.

In my activity, I use the following code to create a bitmap, change it to a circular bitmap and add it to an ImageView (with id “Image” in my Layout file):

var bitmap = BitmapHelper.CreateWhiteBitmap();
bitmap = BitmapHelper.CreateRoundedBitmap(bitmap, 10);
var imageView = view.FindViewById<ImageView>(Resource.Id.Image);
imageView.SetImageBitmap(bitmap);

That’s it! Hope this helps!

Changing the layout for different states of an android button

A button in android can have one or multiple states:

  • android:state_pressed
  • android:state_focused
  • android:state_hovered
  • android:state_selected
  • android:state_checkable
  • android:state_checked
  • android:state_enabled
  • android:state_activated

The layout of a button’s state cannot be changed from within the layout file itself.
A drawable resource file needs to be used to set a layout for the different states.

This resource file should contain a selector with a collection of item elements.
Every item element can target one (or multiple) state(s) of a button by adding the state and its value as attribute. See example below.
It is not necessary to implement all states. An item element with no state attribute is used as default state. See last item element in example below.
This resource file is stored in the Drawable folder of the Resources content (F.E. /Resources/Drawable/button.xml).
Other resources can be referenced and used. In the example below, two custom defined colors are used (@color/custom_theme_button_primary and @color/custom_theme_button_secondary).
When a combination of states are defined on an item element, all states need to be active!

The following example adds three layout states to a button; pressed, disabled and a default state.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true" android:color="@color/custom_theme_button_primary">
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
      <solid
          android:color="@color/custom_theme_button_secondary" />
      <padding
          android:left="10dp"
          android:top="10dp"
          android:right="10dp"
          android:bottom="10dp" />
    </shape>
  </item>
  <item android:state_enabled="false" android:color="@color/custom_theme_button_primary">
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
      <solid
          android:color="@color/custom_theme_button_secondary" />
      <padding
          android:left="10dp"
          android:top="10dp"
          android:right="10dp"
          android:bottom="10dp" />
    </shape>
  </item>
  <item android:color="@color/custom_theme_button_secondary">
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
      <solid
          android:color="@color/custom_theme_button_primary" />
      <padding
          android:left="10dp"
          android:top="10dp"
          android:right="10dp"
          android:bottom="10dp" />
    </shape>
  </item>
</selector>

Setting the color attribute on the item element sets the text color. Setting the color attribute in the solid element within the shape element will set the background color for this shape.
Note: The margin cannot be set in a drawable resource file.

In the layout file, the button needs to contain a reference to the drawable resource file:

<Button
    style="@style/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10.0dp"
    android:layout_marginRight="10.0dp" 
/>

This example requires a drawable resource with the name “button”. Simply create a xml file with the name “button.xml” in Resources/Drawable and add your selector and items.

Android Activities, it’s all about overriding event methods

In my previous post, I talked about class Attributes on Activities.
This post is about overriding event methods to influence the behavior of the Activity.

Activity LifeCycle

When a new Activity is created, the template overrides one event method; OnCreate.

[Activity]
public class MyActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
       .....
    }
}

The OnCreate is part of the Activity LifeCycle.
It is important to understand the Activity LifeCycle, it is one of the fundamentals of an android application.
The OnCreate method works like the Page_Load method of a WebForms page.
This is ideal for setting up the Activity.

For instance:

  • loading layout files
  • updating controls
  • binding event handlers

All event methods of the Activity LifeCycle:

  • OnCreate
  • OnStart
  • OnResume
  • OnPause
  • OnStop
  • OnDestroy
  • OnRestart

When an activity changes state, the corresponding event method is called.
All these methods can be overridden and implemented.

The Activity exposes a lot more overridable event methods.
These are methods I use a lot:

Options menu

The following event methods are used for controlling the options menu:

public override bool OnPrepareOptionsMenu(IMenu menu)
{
       // add your options items to the menu here
      return base.OnPrepareOptionsMenu(menu);
}

public override bool OnOptionsItemSelected(IMenuItem item)
{
    // detect selected menu item and handle action
    return base.OnOptionsItemSelected(item);
}

The OnPrepareOptionsMenu is called when the options menu is created. Custom options can be added to the menu argument.
When an option item is clicked, the OnOptionsItemSelected is called with the selected option item as argument. I usually use a switch on item.Id to detect which item is selected.

The back button

The following event method is called when the back button is pressed:

public override void OnBackPressed()
{
    // handle back button
    base.OnBackPressed();
}

the base.OnBackPressed() provides the default back button behavior. Remove this line when you want to disable the default back button behavior, but I do not recommend it. People expect this behavior from the back button.

Creating Dialogs

This following event method is called when ShowDialog() is called in the current Activity.

public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
    // Create and return dialog here.
}

This method is used to create a dialog.

This should help you get on your way with creating your Activities.

Android Activities, it’s all about the attributes

As promised in my previous post (way too long ago, I know! I’m Sorry!!!), I would talk more about the Activities for Android applications in .Net (By Xamarin).
I want to start with one of the most important parts of the application, the Activities.

[Activity]
public class MyActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
       .....
    }
}

This is the very basic of an Activity. It inherits from Activity and has an attribute Activity. The Activity base class provides many overridable methods, like onCreate, which is called when the Activity is created (think of the Page_Load in WebForm pages).

The Activity attribute has many interesting properties, some of them are listed below:

  • Label, this provides the label for the application, shown in the Android app screen
  • MainLauncher, this is an indication whether the Activity is the main activity and will be started on application startup.
  • Icon, Sets the icon for the application
  • Theme, sets the theme for the application, this can be a custom theme or a predefined theme.
  • ConfigurationChanges, sets which changes are handled by the application itself.
[Activity(Label = "My application",
          MainLauncher = true,
          Icon = "@drawable/icon",
          ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize,
          Theme = "@android:style/Theme.NoTitleBar")]
public class MyActivity : Activity
{
       .....
}

This is an example of the Activity with attributes. No custom code is needed to make this work.

The ConfigurationChanges is set to “Orientation” and “ScreenSize”, this means that orientation changes are handled by the Activity. I use this a lot with WebViews, this stops the application from reloading the page when the orientation changes.

The Theme “NoTitleBar” removes the titlebar from the application. This makes it possible to create your own title bar.
A list of all available predefined themes can be found here

Creating native iOS and Android apps in Visual Studio using C#

Lets go Mobile!

One of my interests in software development is in mobile devices, websites and applications. I have blogged about it in several topics. But this was all about mobile websites and optimizing your website for mobile devices.

In my search for new and interesting things, I ended up with an idea to develop a native app. Because I don’t own any apple device (proud of that!), I wanted to develop a native Android application.

A good starting point for creating Android apps is, of course, the Android docs. But there is one disadvantage, it is Java. I don’t really hate Java, but it is just not for me. I don’t have an IDE set up for Java, I don’t know the language as well as c#, so I didn’t really feel like working with c#.

Xamarin

That is when I found Xamarin. It was actually Scott Hanselman who blogged about it. If you don’t know who Scott Hanselman is, please read his blog! Even better, if you have the change, go and see him when he is speaking.

Xamarin lets you develop native apps in Visual Studio using c#. Everything is strongly typed and works how you expect it to work. The debugger starts the Android emulator and lets you easily test your application.

Just one bad thing about Xamarin, the pricing! It is very expensive, but you can download a 30 day trial.

Setting up your environment

Before you can use Xamarin, you need to set up your environment. I assume you already have Visual Studio installed.

To start using Xamarin, you need to install the following:

First install the Java JDK.  In my case I needed to updated the PATH environment variable (Control Panel -> System -> Advanced System Settings -> Environment Variables) and add the bin folder to this variable. In my case C:\Program Files\Java\jdk1.7.0_51\bin.

After that, unzip theAndroid SDK to a location of choice. Run the SDK Manager as administrator. And install all desired packages.
The installed APIs can be selected from within Visual Studio in the Project Properties.

Now this is done, we can install Xamarin. When this the installation is completed, start Visual Studio and configure it. Go to tools -> options and select Xamarin. In the Android Settings tab Select the Android SDK location. And that’s it. Ready to go!

Project Settings

When you open Visual Studio and select new project, you will find a new option in templates, Android. By selecting this option, you will find several Android applications. Most of it just change the API level.

This can simply be changed in the properties window of the Project.

android-properties
Updating the “Minimum Android to target” property will change the targetted API level. My suggestion: keep the API level as low as possible.  This enhances accesibility.

The Xamarin docs are a good place to start. They have a lot of good tutorials to get started. In my next posts, I will post about native apps and code!

Mobile devices, detection and views in .Net MVC

Mobile is hot, and will probably only get hotter. Sites need to be viewable on any kind of devices, so mobile detection is a hot issue.

Headers

But how do we detect mobile devices?

Every http request send to a page or website contains headers. These headers give us information about the sender. A nice tool to intercept a request and check the headers is fiddler. I have been using this tool for some years now, and I gained a lot of knowledge about requests and responses.


GET http://vicreative.nl/ HTTP/1.1
Host: vicreative.nl
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4

This is an example of a request to my website. This request is sent by Chrome.

The header we are looking for is the User-Agent. This header gives us information about the indentity of the browser who send the request. In above example, you can see that the request is send with a Chrome browser. This header will also tell us when the request is send by a mobile browser. I used a mobile device emulator to fake a mobile request:

GET http://www.vicreative.nl/ HTTP/1.1
User-Agent: Opera/9.80 (Android 2.3.7; Linux; Opera Mobi/46154) Presto/2.11.355 Version/12.10
Host: www.vicreative.nl
Accept: text/html, application/xml;q=0.9, application/xhtml+xml, multipart/mixed, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Device-Stock-UA: Opera Mobile Emulator (no stock UA available)

Another header to keep in mind is the following:


X-Requested-With: XMLHttpRequest

This header information tells us that this is an ajax request. This is also used to determine the IsAjaxRequest property in a MVC controller.

So many devices

Now that we know that every device and browser sends its own User-agent header, you will probably think that it’s impossible to know all devices and browsers and operation systems. Well, you’re right.

I think that’s why the mobile device detection of Microsoft does not work so great. They just can’t update it enough to make it work for all devices.

So do not use HttpCapabilitiesBase.IsMobileDevice. It will only work if you override it and set the correct value.

There is a NuGet package which contains many devices and is updated regularly: 51 degrees.mobi

It also comes with a config, which allows you to set actions for mobile devices, like redirects.

Setting Mobile context

Whether a browser is mobile, can be manually overridden:

HttpContext.SetOverriddenBrowser(this.Request.Browser.IsMobileDevice
                                        ? BrowserOverride.Mobile
                                        : BrowserOverride.Desktop);

The 51 degrees framework will automatically do that, so you don’t really have to do this, but it can come in handy when you want to force it for some reason.

The Browser object has a lot more useful properties for determining which view to display, for instance the property Platform.

Creating Display Modes

As described above, the Browser object has a lot of information about the requested device.
At application start, we can create specific display modes for device types. For instance for Andriod devices:

DisplayModes.Modes.Insert(0, new DefaultDisplayMode("android")
{
    ContextCondition = Context => Context.Request.Browser.Platform == "Android"
});

Keep it clean and create a (static) class in the App_start folder called DisplayModes which contains a method RegisterDisplayModes which registers all display Modes:

public class DisplayModes
{
    public static void RegisterDisplayModes(DisplayModeProvider displayModeProvider)
    {
        displayModeProvider.Modes.Insert(0, new DefaultDisplayMode("android")
        {
            ContextCondition = Context => Context.Request.Browser.Platform == "Android"
        });
        .....
    }
}

Now call this method from the App_Start in the Global.asax file:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    DisplayModes.RegisterDisplayModes(DisplayModeProvider.Instance);
    .....
}

Now that we have registered a display mode for android, we can create android specific views.

Know that the first matching DisplayMode will be used. So the order of registration is very important! The mobile display mode is already registered.

Mobile views

Let’s make some mobile views now.

Creating views for devices is really simple, just add the name of the view before the extension of the file and the ViewEngine will automatically pick up the view for the correct device.

mobile-views

This example has a default Index view (index.cshtml) a mobile view for all mobile devices (Index.mobile.cshtml) and a android specific view (Index.android.cshtml).

This works for all views, including layouts, partial views, shared views, strongly typed views etc.

Because we registered the android DisplayMode at position 0 (first), all android devices will be provided with this view.  When the device is not an android device, but is a mobile device, the mobile view will be presented. For all other devices, the normal index view will be displayed.

Testing

It’s kinda difficult to test this from your developer laptop/pc, but there are many tools who simulate mobile devices. I like the mobile emulator from Opera. It has a lot of presets for mobile devices.

But there are many other emulators, even microsoft has its own.

Caching issues MVC 4

Now that you have created and published your mobile friendly application, you deploy it to your server and quickly check it on your mobile to see if it really works. And it works! Hooray!

Soon people start complaining about seeing strange views. It looks like a mixture of mobile and default views.

This is because of a bug in MVC4. The MVC team has released a patch for it, available here on NuGet.

Automatic Bundling and Minification in .Net

One of the cool new features of .Net 4.5 is the bundling and minification feature. This can save so many requests to your server and saves you many kbs without creating a debug hell. The amount of data is getting more and more important, because of the mobile devices. People pay lots of money on data bundles for their mobile device, we better not waste it. It also decreases loading time!! Reasons enough to start using bundling and minification!

First thing you need to do is download and install the Microsoft ASP.NET Web  Optimization Framework nuget package.

The bundles are registered at application startup. This event is handled in the Application_Start method in the Global.asax. I always try to keep my Global.asax as clean as possible and split all registrations to seperate files in the App_Start folder. So I created a static BundleConfig class in the App_Start folder. This class contains one method, Register with the current Bundles as argument.

BundleConfig.RegisterBundles(BundleTable.Bundles);

BundleConfig

The BundleConfig class registers all JavaScript and Stylesheet bundles, Both Bundles can be added to the same BundleCollection, but both bundles have their own classes. JavaScript bundles are created by using the ScriptBundle class and Stylesheet Bundles are created by using the StyleBundle class.

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));

This creates a JavaScript bundle named “~/bundles/jquery”  and includes one file, “~/Scripts/jquery-{version}.js”.  {version} is automatically resolved to the version of the jquery file in the scripts folder.

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

This creates a Stylesheet bundle names “~/content/css”” and contains one file “~/Content/site.css”. Adding more files is easy, just add more files to the include and separate them by a comma.

Adding bundles to a view

The only thing left to do, is adding the bundles to a view.

MVC (Razor)

@Scripts.Render("~/bundles/jquery")

WebForms

<%: Scripts.Render("~/bundles/jquery") %>

The above code renders the JavaScript bundle.

MVC (Razor)

@Styles.Render("~/Content/css")

WebForms

<%: Styles.Render("~/Content/css") %>

The above code renders the Stylesheet bundle.

All the requests to the bundles have a querystring parameter (v=CkVTG71m7lHB5jSCpyOSxbeCVJLIPag7u7NL4ykFenk1). This is to make sure that no old versions of this file are cached and retrieved.

Config files

Bundles can also be configured in config files. This allows you to make changes to your bundle without having to rebuild the project. It also allows frontend developers to easily include, remove or change files in a bundle without having to use visual studio.

An example of a bundle.config file

<?xml version="1.0" encoding="utf-8" ?>
<bundles version="1.0">
  <styleBundle path="~/Content/css">
    <include path="~/Content/Site.css" />
  </styleBundle>
</bundles>

Debugging

One of the biggest problems of minified files is debugging. It’s almost impossible to debug those files.

That’s when the best feature of this minification framework comes in place. When compilation is set to debug (in web.config), the files will not be minified, which makes it a lot easier to debug.

<system.web>
    <compilation debug="true" />
    <!-- Lines removed for clarity. -->
</system.web>

Creating custom bundle transforms

Custom transforms can be created by implementing the IBundleTransform interface.,

using System.Web.Optimization;

public class MyByndleTransform : IBundleTransform
{
   public void Process(BundleContext context, BundleResponse response)
   {
       // Process bundle tranform here
   }
}

The custom transform can now be added to the transform of a bundle

var myBundle = new Bundle("~/My/Files/To/Include");
lessBundle.Transforms.Add(new MyBundleTransform());

This bundle can now be added to the bundles collection in the BundleConfig file.

Why creating custom bundle transforms? Just think of less or coffeescript, or whatever bundle you want.