Views

Xamarin: Android Activities, Context, Intents and Views

xamandroid

If you are coming from C#/Silverlight, Android can be a little diffusing. Android does not have the same structure than a Windows or Windows Phone app.

Activities

Android has Activities. Activities are the key classes of Android were all actions take place. Unlike other apps or programs, you do not have a “Main” program that is your starting point when launched.

In Android, the starting point is an Activity. The Activity needs to be declared as the starting point. When you start a new project in Xamarin, an Activity called “MainActivity” gets created automatically.

This Activity has some attributes:

[Activity (Label = "gettingstarted", MainLauncher = true)]

The ‘Label’ attribute is what you will see in the Title bar when launching the app. The attribute ‘MainLauncher=true’ tells the application to start from here. Think of this as your MainPage.xaml.cs in a Windows Phone app.

Every Activity has its own OnCreate event, where you can put all your starting, button handlers, stylings etc. in.

But an Activity still has more. It has events like OnStart(), OnPause(), OnRresume() and OnStop() and OnDestroy() and OnRestart(). I won’t get into deep this time, as the Xamarin documentation has already a very good overview of those events: http://docs.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/.

Those events are important to understand for a lot of your application logic, like:

  • saving data that has to be persistent
  • starting and pausing animations
  • register and unregister external events
  • fetch data that are passed from other Activities
  • and more (we will cover some of them in my further posts)

I absolutely recommend to go to the link above to read and understand those events.

Context

The Context is often needed in an Android application and allows your code to be run within an Activity.

The Context allows you for example:

  • to access Android services,
  • to access Application resources like images or styles,
  • to create views
  • to assign gestures to an Activity

Without Context, often code does not get accepted by the IDE or makes your code getting ignored while running the app. Luckily, all methods that I used so far have been telling me if they want a Context, so you need only learn to find out if you need Context for the Activity resources or Application resources.

Intents

But what if we want to have another page (like a separate about page for example)? How can we navigate between pages or call external functions?

This is what Intents are for. Intents are sending messages through the application if another function needs to be started, like the launch of a second page. Within these intents, we have declare the actions that the app needs to do, and if we need a callback, this will also be passed with an Intent.

Let’s hold this high level, here are some lines of code that navigate to a second page (Activity):

var second = new Intent(this, typeof(SecondActivity)); StartActivity(second);

With this code, we are creating an new Intent with Context to our current running Activity to launch the SecondActivity.

To send data between Activities, we use the PutExtra() method of Intents:

var second = new Intent(this, typeof(SecondActivity)); 

second.PutExtra("FirstPage", "Data from First Page"); 

StartActivity(second);

Of course, we need also some code to read the passed data on our second page:

Intent.GetStringExtra("FirstPage") ?? “Data not available”;

We could now use this data on our second page by assigning it to a control or function.

Passing data between activities works similar to passing QueryStrings in NavigationsService.Navigate() method on WindowsPhone, so you should get familiar with it very fast.

Views

The last part that is very important are Views. In a View you declare how the Activity looks like. Think of it as your MainPage.xaml page in a Windows Phone app.

Views can be very different, too. Let’s start with the simple View. In our getting started project, we also have a Layout file that holds our first View:

<?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>

The View has a main LinearLayout which is acts as  ContentPanel. All other controls like Buttons, TextViews etc. are going into this. There are a lot of properties that can be set, we’ll leave it this easy for now. If you want to know more about those properties, you can have a look at the Android documentation here: http://developer.android.com/guide/topics/ui/declaring-layout.html

This part is totally the same as with the one matching part in the Android SDK, so you will need to get familiar with the Android documentation as well.

To make a View visible, we need to assign it to an Activity. In our sample app, we are doing this with this line of code in our OnCreate event:

SetContentView (Resource.Layout.Main);

This is the easy way for Views. But there are more complex Views in Android, too.

Views are also used in ListViews, where you declare the look of the items and the list in a Layout file, or also if you use the ActionBar with a tab navigation, and also in the menu of an ActionBar. I will cover all of these in my further blog posts, as we also need Adapters to get data binded to Views.

I hope you this post helps you to understand  the high level structure of an Android application.

Until the next time, happy coding!

Posted by msicc in Android, Dev Stories, Xamarin, 0 comments

Xamarin: Resources of an Android app project

As I mentioned already in my first blog post about Xamarin, Android has a different project structure – even if you use Xamarin.

A very important part of this structure are resources. We have different kind of resources in an Android app:

  • Icons & Images
  • Layout (XML files)
  • Values (string resource files)

Let’s start with Icons & Images.

As you can see in the solution window, there is a folder called ‘Resources’. Here you will put all kind of resources, like images, icons, layouts and so on.

The corresponding class for images in Android is called ‘drawable’, that holds a reference to’ Icon.png’. The project structure is based on that, that’s why the resources folder has all images inside the folder ‘drawable’. As Android has various screen sizes, you may have a folder for structure like ‘drawable’, ‘drawable-hdpi, ‘drawable-ldpi’ and so on. Android scales your image resources to match the screen automatically if you do not define alternate layouts.

To make your files available in your app, you need to set the Build Action to ‘Android Resource’:

Screenshot (278)

Let’s have a look to the Layout files:

Layout files are XML files that contain the UI of a page, control or a view. You can use these XML files for example to define items of a ListView or simply the application page. Every new project has a ‘Main.axml’ file.

There are two ways to create a layout. The first one is using the visual designer:

Screenshot (280)

This works for basic layouts like adding the button above. Also, if you don’t know the properties of a control you added, you will be able to add it here to get started.

If you are familiar with writing your UI in code (like XAML)  and want to do so in your Android app, just click the ‘Source’ tab at the bottom in the visual designer. You will see something like this:

<?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>

If you want to add and modify a control, but don’t know how the properties are, this page has a list of all controls, which are called ‘widgets’ in Android. That’s also the corresponding namespace: android.widget.

Like in an Windows Phone app, you also have a string resource file in Android projects. This file is once again a XML file, but with a different structure:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Click Me!</string>
<string name="app_name">gettingstarted</string>
</resources>

All strings need to be declared inside the <resources> tag. The definition is always like <string name=”yourstringname”>stringcontent</string>. Empty strings are not supported and will throw an error at building your project.

Let’s have a look on how we can work with our resources, based on our gettingstarted project. We have the following code inside our MainActivity class:

int count = 1;

		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.Text = GetString (Resource.String.hello);

			button.Click += delegate {
				button.Text = string.Format ("{0} clicks!", count++);
			};
		}

As you can see, the we are defining our view from our Layout file ‘Main.axml’ by using the SetContentView() method. The file is added to our resources list as Layout with the name we defined.

Our MainActivity does not know that we have a button inside our layout. To make the button visible to our MainActivity, we need to reference it. This is done by declaring a Button instance and using the FindViewById<T>(ResourceName) method.

If you have not given your button a name, now is the right time to do so. In our example the button has the name “myButton”.  The syntax is very important, make sure you add “@+id/” to the name.

android:id="@+id/myButton"

Now our button is visible to our MainActivity code page and can be accessed. The sample project references the button content in the Layout file:

android:text="@string/hello"

After referencing our button, we could also use the following code to get the button content from the resource file:

button.Text = GetString (Resource.String.hello);

Whenever your want to get a string from the resource file in an Activity, the GetString() method is used.

I hope this post helps you to understand how resources are used in an Android app and how to handle it a Xamarin project.

Happy coding everyone!

Posted by msicc in Android, Dev Stories, Xamarin, 0 comments

New Series: developing for Android with Xamarin

xamandroid

Prolog

In the last few month I was developing not only my personal projects, but also on my daily 9to5 job. I am working on an internal app that will help to improve the customer experience amongst the customers of my employer Telefónica.

The project has a simple setup in phase I, with collecting data and sending them via mail. The challenge for me was how to get the Windows Phone app (yes, Windows Phone was first!) to Android.

I knew it would take some time to get started with Android development, and was searching for possible solutions to speed things up. I knew from Xamarin already, and was able to obtain a 1-year license for Android (maybe iOS will follow later).

Some of my fellow WinPhans and WinPhanDevs will scream out very loud at the moment. I understand that. But honestly, I could not let go away this huge opportunity for me – as it touches both my daily job and my private developer story. To calm you down: I will always love Windows Phone and Windows and develop for it first. I will always remain a WinPhanDev. But I need to go forward, and this is a big step.

Let’s go back to the topic.

With this blog post, I am kicking off a new blogging series for Android development with Xamarin. The huge advantage of using Xamarin is that I am able to use my C# knowledge to develop apps for other platforms – which makes it a little easier to get things done.

However, if you start with another platform, you still have to learn the platform structure. Without knowing or be willing to learn it, you will be lost very fast. Every OS has its own specific UI rules, save handling and so on. This is what I will blog about.

The Windows Phone app I ported to Android has a item Pivot, which I ported over to Android. It has a little different appearance, but it works in a similar way with tapping the header or a swiping gesture to move between the items/pages.

To get there, I had to learn a lot about Android – and I will share it all with you out there.

My series will cover the following topics:

Installing Xamarin

Installing Xamarin is pretty easy – but will take some time. Click on this link to download the Xamarin IDE. The IDE will ask you for which platform you want to develop for (let’s choose only Android for the moment) and then download a huge amount of additional SDKs like the Java and the Android SDK (Android apps are Java based, if you didn’t knew).

Screenshot (267)

On the screenshot above you can see the starting page of Xamarin Studio. On the left side you have the list of recent solutions, in the middle you see Xamarin news and finally the pre-built apps section.

Xamarin Studio has a lot together with Visual Studio, and you also can take a lot of settings to adjust the appearance for your needs. Let’s start a new project by clicking on the ‘New’ button

Screenshot (270)

Xamarin will set up a .sln file with everything we need for the moment. After creating the project has been created, you’ll see these lines of code:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace gettingstarted
{
	[Activity (Label = "gettingstarted", MainLauncher = true)]
	public class MainActivity : Activity
	{
		int count = 1;

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

 

These few lines should help to get started with the basic structure of an Android App.

Android has Activities. Activities can be seen as the code behind files in a C# project. Here begins all the action of an Android app. Xamarin automatically ads the Label (project name) and in this case, also the MainLauncher property, which will run this code on app start up.

To get something displayed in our app, we need to load a Layout or create the view from the code. This is what the SetContentView() method is about. Without this, the app will compile but displays nothing. In this demo app, a basic layout with a button inside is created:

<?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>

 

We already have the first difference to other C# projects here. In order to make the button visible for our code in the Activity, we need to search our resources for the button. This is done by the FindViewById<T>() method. As soon as it is visible to our code, we are able to create a delegate for our button Click event.

The button counts then the clicks on it and changes the text based on the number of clicks.

To understand more about the structure of an Android App, I highly recommend to read the documentation. For me, especially these links were helpful:

There are some more resources that are helpful, but for getting started those four links should be enough. I will cover some of the topics above also with my upcoming posts and link additional resources as well.

As with the Windows Phone development, also StackOverflow is a big help as well as the Xamarin  Android forums.

Until the next post, happy coding!

Posted by msicc in Android, Dev Stories, Xamarin, 0 comments