Sunday, July 13, 2014

Android Drawable Cache (Xamarin / Mono)

The code below is useful if you need to cache images in Android. Weak references are used to help protect against memory leaks.

Drawable Cache Class:
public class DrawableCache
{
 public Context Context { get; set; }
 Dictionary<object, WeakReference<Drawable.ConstantState>> _cache = new Dictionary<object, WeakReference<Drawable.ConstantState>>();

 public DrawableCache(Context context)
 {
  Context = context;
 }

 public void Put(object key, Drawable drawable)
 {
  _cache[key] = new WeakReference<Drawable.ConstantState>(drawable.GetConstantState(), false);
 }

 public Drawable Get(object key)
 {
  WeakReference<Drawable.ConstantState> value;
  if (_cache.TryGetValue(key, out value))
  {
   Drawable.ConstantState target;
   if (value.TryGetTarget(out target))
   {
    return target.NewDrawable(Context.Resources);
   }
   _cache.Remove(key);
  }
  return null;
 }
}
Optional Drawable Cache Key class
public class DrawableCacheKey
{
 public int Key { get; set; }
 public int Flags { get; set; }

 public DrawableCacheKey(int key, int flags)
 {
  Key = key;
  Flags = flags;
 }

 public override int GetHashCode()
 {
  int hash = 17;
  hash = hash * 23 + Key.GetHashCode();
  hash = hash * 23 + Flags.GetHashCode();
  return hash;
 }

 public override bool Equals(object obj)
 {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  var cast = obj as DrawableCacheKey;
  return cast != null && Key == cast.Key && Flags == cast.Flags;
 }
}

Sunday, January 5, 2014

Simple C# Artificial Neural Network

Artificial intelligence interests me, especially when modeled from or inspired by biology. Artificial neural networks are one such example:

"Artificial neural networks are computational models inspired by animals' central nervous systems (in particular the brain) that are capable of machine learning and pattern recognition. They are usually presented as systems of interconnected "neurons" that can compute values from inputs by feeding information through the network." - Wikipedia

I'm not going to try explain how artificial neural networks work. The topic is much too complex and there is already good documentation available elsewhere. If you are interested in learning more about artificial neural networks then I recommend the following article: Neural Network Back-Propagation Using C#. Most of the code in this post is based on the ideas presented in that article.

There are many different types of artificial neural networks. My implementation is a feed-forward, multi-layer, perceptron network which uses the back-propagation algorithm for learning. I believe this is one of the most common types of neural networks and is a good place to start for beginners. I'm still a beginner myself; I understand the basic concepts but the math is still slightly mysterious. Hopefully I can find time in the future to learn more about neural networks and artificial intelligence.

I tried to make the code as simple as possible. Code is below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NeuralNetwork
{
    class Program
    {
        static void Main(string[] args)
        {
            var network = new NeuralNetwork(2, 3, 1);

            Console.WriteLine("Training Network...");
            for (int i = 0; i < 100000; i++)
            {
                network.Train(0, 0);
                network.BackPropagate(1);

                network.Train(1, 0);
                network.BackPropagate(0);

                network.Train(0, 1);
                network.BackPropagate(0);

                network.Train(1, 1);
                network.BackPropagate(1);
            }

            double error;
            double output;

            output = network.Compute(0, 0)[0];
            error = network.CalculateError(1);
            Console.WriteLine("0 XOR 0 = " + output.ToString("F5") + ", Error = " + error.ToString("F5"));

            output = network.Compute(1, 0)[0];
            error = network.CalculateError(0);
            Console.WriteLine("1 XOR 0 = " + output.ToString("F5") + ", Error = " + error.ToString("F5"));

            output = network.Compute(0, 1)[0];
            error = network.CalculateError(0);
            Console.WriteLine("0 XOR 1 = " + output.ToString("F5") + ", Error = " + error.ToString("F5"));

            output = network.Compute(1, 1)[0];
            error = network.CalculateError(1);
            Console.WriteLine("1 XOR 1 = " + output.ToString("F5") + ", Error = " + error.ToString("F5"));
        }
    }

    public class NeuralNetwork
    {
        public double LearnRate { get; set; }
        public double Momentum { get; set; }
        public List<Neuron> InputLayer { get; set; }
        public List<Neuron> HiddenLayer { get; set; }
        public List<Neuron> OutputLayer { get; set; }
        static Random random = new Random();

        public NeuralNetwork(int inputSize, int hiddenSize, int outputSize)
        {
            LearnRate = .9;
            Momentum = .04;
            InputLayer = new List<Neuron>();
            HiddenLayer = new List<Neuron>();
            OutputLayer = new List<Neuron>();

            for (int i = 0; i < inputSize; i++)
                InputLayer.Add(new Neuron());

            for (int i = 0; i < hiddenSize; i++)
                HiddenLayer.Add(new Neuron(InputLayer));

            for (int i = 0; i < outputSize; i++)
                OutputLayer.Add(new Neuron(HiddenLayer));
        }

        public void Train(params double[] inputs)
        {
            int i = 0;
            InputLayer.ForEach(a => a.Value = inputs[i++]);
            HiddenLayer.ForEach(a => a.CalculateValue());
            OutputLayer.ForEach(a => a.CalculateValue());
        }

        public double[] Compute(params double[] inputs)
        {
            Train(inputs);
            return OutputLayer.Select(a => a.Value).ToArray();
        }

        public double CalculateError(params double[] targets)
        {
            int i = 0;
            return OutputLayer.Sum(a => Math.Abs(a.CalculateError(targets[i++])));
        }

        public void BackPropagate(params double[] targets)
        {
            int i = 0;
            OutputLayer.ForEach(a => a.CalculateGradient(targets[i++]));
            HiddenLayer.ForEach(a => a.CalculateGradient());
            HiddenLayer.ForEach(a => a.UpdateWeights(LearnRate, Momentum));
            OutputLayer.ForEach(a => a.UpdateWeights(LearnRate, Momentum));
        }

        public static double NextRandom()
        {
            return 2 * random.NextDouble() - 1;
        }

        public static double SigmoidFunction(double x)
        {
            if (x < -45.0) return 0.0;
            else if (x > 45.0) return 1.0;
            return 1.0 / (1.0 + Math.Exp(-x));
        }

        public static double SigmoidDerivative(double f)
        {
            return f * (1 - f);
        }
    }

    public class Neuron
    {
        public List<Synapse> InputSynapses { get; set; }
        public List<Synapse> OutputSynapses { get; set; }
        public double Bias { get; set; }
        public double BiasDelta { get; set; }
        public double Gradient { get; set; }
        public double Value { get; set; }

        public Neuron()
        {
            InputSynapses = new List<Synapse>();
            OutputSynapses = new List<Synapse>();
            Bias = NeuralNetwork.NextRandom();
        }

        public Neuron(List<Neuron> inputNeurons) : this()
        {
            foreach (var inputNeuron in inputNeurons)
            {
                var synapse = new Synapse(inputNeuron, this);
                inputNeuron.OutputSynapses.Add(synapse);
                InputSynapses.Add(synapse);
            }
        }

        public virtual double CalculateValue()
        {
            return Value = NeuralNetwork.SigmoidFunction(InputSynapses.Sum(a => a.Weight * a.InputNeuron.Value) + Bias);
        }

        public virtual double CalculateDerivative()
        {
            return NeuralNetwork.SigmoidDerivative(Value);
        }

        public double CalculateError(double target)
        {
            return target - Value;
        }

        public double CalculateGradient(double target)
        {
            return Gradient = CalculateError(target) * CalculateDerivative();
        }

        public double CalculateGradient()
        {
            return Gradient = OutputSynapses.Sum(a => a.OutputNeuron.Gradient * a.Weight) * CalculateDerivative();
        }

        public void UpdateWeights(double learnRate, double momentum)
        {
            var prevDelta = BiasDelta;
            BiasDelta = learnRate * Gradient; // * 1
            Bias += BiasDelta + momentum * prevDelta;

            foreach (var s in InputSynapses)
            {
                prevDelta = s.WeightDelta;
                s.WeightDelta = learnRate * Gradient * s.InputNeuron.Value;
                s.Weight += s.WeightDelta + momentum * prevDelta;
            }
        }
    }

    public class Synapse
    {
        public Neuron InputNeuron { get; set; }
        public Neuron OutputNeuron { get; set; }
        public double Weight { get; set; }
        public double WeightDelta { get; set; }
        
        public Synapse(Neuron inputNeuron, Neuron outputNeuron)
        {
            InputNeuron = inputNeuron;
            OutputNeuron = outputNeuron;
            Weight = NeuralNetwork.NextRandom();
        }
    }
}

Saturday, October 26, 2013

UDP Proxy / Minecraft PE Proxy

Here is a UDP Proxy implemented in Java that can be used for Minecraft Pocket Edition. Inspired by the Node.js implementation. Runs great on Raspberry Pi.
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class UdpProxy
{
 public static void main(String[] args) throws Exception
 {
  boolean testMode = args.length == 0;
  String serverHost;
  int serverPort;
  int proxyPort;

  if (args.length != 3 && !testMode)
  {
   System.out.println("Use: java UdpProxy <serverhost> <serverport> <proxyport>");
   return;
  }

  if (!testMode)
  {
   serverHost = args[0];
   serverPort = Integer.parseInt(args[1]);
   proxyPort = Integer.parseInt(args[2]);
  }
  else
  {
   serverHost = "192.168.1.114";
   serverPort = 19132;
   proxyPort = 19133;
  }

  new UdpProxy(serverHost, serverPort, proxyPort).runServer();
 }
 
 static final int CONNECTION_TIMEOUT = 60000;
 HashMap<InetSocketAddress, ChannelInfo> channelMap = new HashMap<InetSocketAddress, ChannelInfo>();
 InetSocketAddress serverAddress;
 int proxyPort;

 public UdpProxy(String serverHost, int serverPort, int proxyPort) throws Exception
 {
  InetAddress resolvedAddress = InetAddress.getByName(serverHost);
  this.serverAddress = new InetSocketAddress(resolvedAddress, serverPort);
  this.proxyPort = proxyPort;
 }

 public void runServer() throws Exception
 {
  System.out.println("Listening on " + proxyPort + ", forwarding to " + serverAddress);

  ByteBuffer buff = ByteBuffer.allocate(1024*1024); //this is probably more than necessary
  Selector selector = Selector.open();
  DatagramChannel proxyChannel = addChannel(selector, proxyPort);
  long connectionTestTime = System.currentTimeMillis();
  
  while (true)
  {
   try
   {
    selector.select(10000); //selector.selectNow();
    Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
    
    while (keyIterator.hasNext())
    {
     SelectionKey key = keyIterator.next();
     keyIterator.remove();
     
     if (key.isReadable())
     {
      DatagramChannel currentChannel = (DatagramChannel) key.channel();
      InetSocketAddress localAddress = (InetSocketAddress) currentChannel.socket().getLocalSocketAddress();
      buff.clear();
      InetSocketAddress remoteAddress = (InetSocketAddress) currentChannel.receive(buff);
      buff.flip();
      
      if (!fromServer(remoteAddress))
      {
       ChannelInfo info = channelMap.get(remoteAddress);
       if (info == null)
       {
        DatagramChannel tempChannel = addChannel(selector, serverAddress);
        InetSocketAddress tempAddress = (InetSocketAddress) tempChannel.socket().getLocalSocketAddress();
        info = new ChannelInfo(tempChannel, remoteAddress);
        channelMap.put(remoteAddress, info);
        System.out.println("Added key = " + remoteAddress.toString());
        channelMap.put(tempAddress, info);
        System.out.println("Added key = " + tempAddress.toString());
       }
       
       info.rxTime = System.currentTimeMillis();
       info.channel.send(buff, serverAddress);
      }
      else
      {
       ChannelInfo info = channelMap.get(localAddress);
       if (info != null)
       {
        proxyChannel.send(buff, info.remoteAddress);
       }
      }
     }
    }
    
    //Test & remove old connections
    if (System.currentTimeMillis() - connectionTestTime >= CONNECTION_TIMEOUT)
    {
     connectionTestTime = System.currentTimeMillis();
     Iterator<Map.Entry<InetSocketAddress, ChannelInfo>> entryIterator = channelMap.entrySet().iterator();
     while (entryIterator.hasNext())
     {
      Map.Entry<InetSocketAddress, ChannelInfo> entry = entryIterator.next();
      InetSocketAddress address = entry.getKey();
      ChannelInfo info = entry.getValue();
      if (connectionTestTime - info.rxTime >= CONNECTION_TIMEOUT)
      {
       info.channel.close();
       entryIterator.remove();
       System.out.println("Removed key = " + address.toString());
      }
     }
    }
   }
   catch (Exception ex)
   {
    ex.printStackTrace();
   }
  }
 }
 
 public boolean fromServer(InetSocketAddress address)
 {
  return address.getAddress().equals(serverAddress.getAddress());
 }

 public DatagramChannel addChannel(Selector selector, int bindPort) throws Exception
 {
  DatagramChannel channel = DatagramChannel.open();
  channel.configureBlocking(false);
  channel.socket().bind(new InetSocketAddress(bindPort));
  channel.register(selector, SelectionKey.OP_READ);
  return channel;
 }

 public DatagramChannel addChannel(Selector selector, InetSocketAddress address) throws Exception
 {
  DatagramChannel channel = DatagramChannel.open();
  channel.configureBlocking(false);
  channel.connect(address);
  channel.register(selector, SelectionKey.OP_READ);
  return channel;
 }

 public static class ChannelInfo
 {
  public ChannelInfo()
  {
  }

  public ChannelInfo(DatagramChannel channel, InetSocketAddress remoteAddress)
  {
   this.channel = channel;
   this.localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress();
   this.remoteAddress = remoteAddress;
  }

  DatagramChannel channel;
  InetSocketAddress localAddress;
  InetSocketAddress remoteAddress;
  long rxTime;
 }
}

Saturday, March 23, 2013

Show / Hide Android Soft Keyboard

Here is a helpful utility class for showing and hiding the Android soft keyboard. The code is written in C# using Mono for Android but should be easy to convert to Java. Similar behavior can be accomplished using Window.SetSoftInputMode but unfortunately SetSoftInputMode doesn't always play well with a tab / fragment architecture.

This code is my attempt to simplify the process of manually showing and hiding of the soft keyboard, which is much more complicated than it has a right to be (I blame vague documentation). My earlier attempts to accomplish this were laden with frustrating bugs and strange side-effects. Now, (hopefully) all those bugs and side-effects have been corrected.

By default there is a 200 millisecond delay on the ShowSoftKeyboard method; this is to accommodate any fragment transition animations that may occur. Showing the keyboard while running an animation can result in poor performance so the workaround is to wait until the animation is finished. If you are not using fragment transition animations then the delay can be eliminated.

*Code has been tested on a handful of real devices as well as a wide range of emulator versions (2.2+).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Views.InputMethods;
using Android.InputMethodServices;
using Android.Util;

namespace Mobile.Util
{
    public static class ActivityExtensions
    {
        public static void HideSoftKeyboard(this Activity activity)
        {
            new Handler().Post(delegate
            {
                var view = activity.CurrentFocus;
                if (view != null)
                {
                    InputMethodManager manager = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
                    manager.HideSoftInputFromWindow(view.WindowToken, 0);
                }
            });
        }

        public static void ShowSoftKeyboard(this Activity activity, View view = null, int delay = 200)
        {
            new Handler().PostDelayed(delegate
            {
                view = view ?? activity.CurrentFocus;
                if (view != null)
                {
                    if (view.HasFocus)
                        view.ClearFocus(); //bug fix for older versions of android

                    view.RequestFocus();
                    InputMethodManager manager = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
                    manager.ShowSoftInput(view, 0);
                }
            }, delay);
        }
    }

    public static class DialogExtensions
    {
        public static void HideSoftKeyboard(this Dialog dialog)
        {
            new Handler().Post(delegate
            {
                var view = dialog.CurrentFocus;
                if (view != null)
                {
                    InputMethodManager manager = (InputMethodManager)dialog.Context.GetSystemService(Context.InputMethodService);
                    manager.HideSoftInputFromWindow(view.WindowToken, 0);
                }
            });
        }

        public static void ShowSoftKeyboard(this Dialog dialog, View view = null, int delay = 200)
        {
            new Handler().PostDelayed(delegate
            {
                view = view ?? dialog.CurrentFocus;
                if (view != null)
                {
                    if (view.HasFocus)
                        view.ClearFocus(); //bug fix for older versions of android

                    view.RequestFocus();
                    InputMethodManager manager = (InputMethodManager)dialog.Context.GetSystemService(Context.InputMethodService);
                    manager.ShowSoftInput(view, 0);
                }
            }, delay);
        }     
    }
}

Friday, February 22, 2013

Raspberry Pi

My Raspberry Pi arrived in the mail today. These things are great and only cost about $35-$40. Lots of fun.

Raspberry Pi Model B

Wednesday, July 25, 2012

Mono for Android Resource Naming Convention

When you create a default Mono for Android project the included resource files are named using a mixture of uppercase and lowercase letters. Please, do NOT follow this naming convention because this is the cause of a variety of unresolved, mostly minor bugs. Instead name all your resource files using all lowercase letters and underscores. It is much safer to follow this practice as opposed to the one presented by Xamarin.

Wednesday, July 11, 2012

ActionBarSherlock with Mono for Android

3/7/2013 - I updated the blog post so everything should be current and relevant as of today. This was long overdue, sorry.

For instant gratification try downloading the Xamarin sample project. However this will most likely yield an outdated version of the ActionBarSherlock library.

Today I will explain how to bind the ActionBarSherlock Java library so that it can be used with Mono for Android. ActionBar compatibility is important since over 90% of Android users are still running a pre 3.0 platform. It's a luxury Java programmers have enjoyed for awhile now, which can finally be shared with fellow C# programmers.

The required steps are listed below:

Build the ActionBarSherlock Zip

  1. First, if necessary, download and install the latest version of Eclipse along with the ADT Plugin.
  2. Next, download the latest version of ActionBarSherlock. After the download finishes extract the library folder from archive.
  3. Rename the library folder to actionbarsherlock. In this tutorial, the library folder has been renamed/moved to c:\downloads\actionbarsherlock.
  4. Start Eclipse and create a new workspace. In this tutorial, I created a workspace located at c:\projects\actionbarsherlock.
  5. Begin creating a new Android project by clicking File -> New -> Other -> Android -> Android Project From Existing Code. Click Next.
  6. In the "Root Directory" field, browse to c:\downloads\actionbarsherlock. Check the "Copy projects into workspace" field. Click Finish.
  7. Click Project -> Clean and wait for Eclipse to finish building the project. Exit Eclipse after the build is complete. If you encounter any compile errors ensure that you are targetting Java 6+.
  8. Open Windows Explorer, and browse to c:\projects\actionbarsherlock\actionbarsherlock. Select the bin, assets, and res folders and add them to a new Zip file. Name the file actionbarsherlock.zip.
  9. Now browse to c:\projects\actionbarsherlock\actionbarsherlock\libs and locate the file android-support-v4.jar. No action is required yet, but remember this file location for future use.
  10. Later, both the actionbarsherlock.zip and android-support-v4.jar files will be copied into Visual Studio.

Create the Binding Library

  1. Open Visual Studio and create a new JAR Bindings Library project (click File -> New -> Project -> Mono for Android -> Java Bindings Library). Name the project ActionBarSherlockBinding and click OK.
  2. Click Project -> ActionBarSherlockBinding Properties and change the Target API level to 14+.
  3. Add a reference to the Mono.Android.Support.v4 binding library by clicking Project -> Add Reference and switching to the .NET tab. Select the Mono.Android.Support.v4 library and click OK.
  4. Now copy the actionbarsherlock.zip and android-support-v4.jar files (from the previous section) into the Jars folder of the ActionBarSherlockBinding project in Visual Studio.
  5. In the properties pane, right click on the the actionbarsherlock.zip file and change the Build Action to "LibraryProjectZip". Next, right click on the android-support-v4.jar file and change the Build Action to "ReferenceJar".
  6. Open the Metadata.xml file located under the the Transforms folder and replace all of its contents with the XML code below. Save and close the file when finished.
    <metadata>
    
      <!-- Don't bind internal packages/classes -->
      <remove-node path="/api/package[starts-with(@name, 'com.actionbarsherlock.internal')]" />
      
      <!-- Normalize the API, forced to use underscore to avoid name conflicts -->
      <attr path="/api/package[@name='android.support.v4.app']" name="managedName">Android.Support.V4.App</attr>
      <attr path="/api/package[@name='com.actionbarsherlock']" name="managedName">ActionBar_Sherlock</attr>
      <attr path="/api/package[@name='com.actionbarsherlock.app']" name="managedName">ActionBar_Sherlock.App</attr>
      <attr path="/api/package[@name='com.actionbarsherlock.view']" name="managedName">ActionBar_Sherlock.View</attr>
      <attr path="/api/package[@name='com.actionbarsherlock.widget']" name="managedName">ActionBar_Sherlock.Widget</attr>
    
    </metadata>
    
    Note: Additional documentation regarding this step can be found here. Lines 6-11 are trivial but line 4 is important.

  7. Build the solution and verify that there are no errors. There will probably be some warnings but it should still build successfully.

Reference the Binding Library

  1. In Visual Studio, add a new Android Application project to the existing solution (click File -> Add -> New Project -> Mono for Android -> Android Application). Name the project ActionBarSherlockDemo and click OK.
  2. Click Project -> ActionBarSherlockDemo Properties and change the Target API level to 14+.
  3. Add a reference to the binding library by clicking Project -> Add Reference and switching to the Projects tab. Select the ActionBarSherlockBinding project and click OK.
  4. Also add a reference to the Mono.Android.Support.v4 binding library from the .NET tab of the Add Reference dialog.
  5. Rebuild the solution and verify that there are no errors.

Extend the SherlockActivity Class

  1. Open Activity1.cs and change it so that it inherits from the ActionBar_Sherlock.App.SherlockActivity class. Documentation for the ActionBarSherlock library is more or less equivalent to the native ActionBar API.
  2. Items can be added to the ActionBar by creating a menu resource and overriding the OnCreateOptionsMenu method.
  3. Generate the AndroidManifest.xml and then edit it and set the SDK and theme like this:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="internalOnly">
      <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14" />
      <application android:theme="@style/Theme.Sherlock" />
    </manifest>
    
  4. Rebuild the solution, deploy to the emulator or device, and congratulations, you're finished!



By Request - An ActionBar Tab Example

This is a quick and dirty example of ActionBar tabs with Mono for Android using ActionBarSherlock. This code is only intended as a demonstration of basic concepts. Please refer to the official Android ActionBar documentation for best practices and for a more complete example.

using System;

using Android.OS;
using Android.Views;
using ActivityAttribute = Android.App.ActivityAttribute;
using ActionBarNavigationMode = Android.App.ActionBarNavigationMode;
using Android.Support.V4.App;
using ActionBar_Sherlock.App;
using Tab = ActionBar_Sherlock.App.ActionBar.Tab;

namespace ActionBarSherlockDemo
{
    [Activity(Label = "Tab Activity", MainLauncher = true)]
    public class TabActivity : SherlockFragmentActivity, ActionBar_Sherlock.App.ActionBar.ITabListener
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            SupportActionBar.NavigationMode = (int)ActionBarNavigationMode.Tabs;
            SupportActionBar.SetDisplayShowTitleEnabled(true);

            Tab tab = SupportActionBar.NewTab();
            tab.SetTag("TAB1");
            tab.SetText("TAB 1");
            tab.SetTabListener(this);
            SupportActionBar.AddTab(tab);
            
            tab = SupportActionBar.NewTab();
            tab.SetTag("TAB2");
            tab.SetText("TAB 2");
            tab.SetTabListener(this);
            SupportActionBar.AddTab(tab);
        }

        public void OnTabSelected(Tab tab, Android.Support.V4.App.FragmentTransaction ft)
        {
            string tag = tab.Tag.ToString();

            Fragment f = SupportFragmentManager.FindFragmentByTag(tag);
            if (f != null)
            {
                ft.Show(f);
                return;
            }

            if (tag == "TAB1")
                f = new TestFragment1();
            else if (tag == "TAB2")
                f = new TestFragment2();

            ft.Add(Resource.Id.fragmentPlaceholder, f, tag);
        }


        public void OnTabUnselected(Tab tab, Android.Support.V4.App.FragmentTransaction ft)
        {
            string tag = tab.Tag.ToString();

            Fragment f = SupportFragmentManager.FindFragmentByTag(tag);
            if (f != null)
            {
                ft.Hide(f);
                return;
            }
        }

        public void OnTabReselected(Tab tab, Android.Support.V4.App.FragmentTransaction ft)
        {
            //Do nothing
        }
    }

    public class TestFragment1 : Fragment
    {
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
        {
            return inflater.Inflate(Resource.Layout.test1, container, false);
        }
    }

    public class TestFragment2 : Fragment
    {
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
        {
            return inflater.Inflate(Resource.Layout.test2, container, false);
        }
    }
}