Sunday, January 8, 2017

Developing Android app in C# with Visual Studio with Xamarin

Xamarin let’s you create apps in C# for iOS, Android & Mac.


Project Structure:

image
This is how a project structure of an Android app will look. When you create a new Android application in Visual Studio, Xamarin set’s it up for you by default.
Few things to make a note of – only a few for now.

AndroidManifest.xml

Every Android project must contain this file. The manifest lets you define the metadata of your application like Application Name, Package Name, Required Permissions, Activities etc. This is similar to a App.config or Web.Config files but differs in certain ways. In Xamarin you can easily edit manifest information by going to the properties of the project. Please note that there are other values that are auto generated by Xamarin from the attributes that you define in classes. You can learn more about it from the documentation.

Resources

It’s a good practice to keep non-code resources like images, icons, and constants external to your code. Android expects you to store them in a specific sub folders within the resources folder. Notice 6 different Drawable folders which are kept separated based on the DPI displays. These folder will include respective sized bitmaps & PNG images. Perhaps the most powerful Resource to be noted is the Layouts.

Layouts

Layout is the User Interface – Yes that’s right! Whatever user sees is what is designed inside layout files. These are xml based and have the extension .axml . It decouples the presentation layer – much similar to XAML in Windows Phone.
Here’s an example of a layout:
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/MyButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/Hello" />
</LinearLayout>

Activity

Activity is the class responsible for setting the UI content for the users to interact! You can consider this as a code-behind for the Layout written in the resources. So the activity class will contain the presentation logic of your view. It is the class that is referenced by the Android system to do the user interaction. Activities are created or destroyed by the Android system. It’s important to understand the Activity Life Cycle to effectively handle user data in the changing states such as RunningPausedBackgrounded  & Stopped.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace HelloXamarin.Android
{
    [Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
         
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
           // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
        }
    }
}
All your Activity classes should derive from Activity base class. Notice the MainLauncher = true set in custom attribute – this is to set the starting screen of your app!
OnCreate() is called when the activity is created. It’s always overridden to perform startup initializations such as
  • Creating  Views
  • Initializing variables
  • Binding static data to lists
Notice the SetContentView() – It places your layout on the screen. Layouts can be accessed using the static variable Resources.Layout.<yourLayoutName>.
Now let’s add a Click event handler to the button placed in the Layout. Shall we?
To get the reference of the button placed in the layout use the helper method FindByViewId<T>() and pass the Id of the button you set in the resource. Once you get the handle – just add the event to the Click handler.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private int count = 0;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
           // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);
            button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
        }
    }
To navigate to another screen and pass some extra information along, use StartActivity() with an intent that contains the extra information. Extra information is nothing but the data that you want to pass between your screens.
1
2
3
4
5
6
button.Click += (s, e) =>
      {
          var intent = new Intent(this, typeof(DetailActivity));
          intent.PutExtra("userCount", count++);
          base.StartActivity(intent);
      };
Finally to receive the extra information that was passed from the previous screen you can use Intent.GetStringExtra or other type based methods. Here’s the full code:
1
2
3
4
5
6
7
8
9
10
11
12
13
[Activity(Label = "DetailActivity")]
public class DetailActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Detail);
        var t = FindViewById<TextView>(Resource.Id.textView1);
        t.Text = string.Format("{0}:{1}","You clicked ",Intent.GetIntExtra("userCount", 0));
    }
}


No comments:

Post a Comment