Share via


Getting started with Xamarin Android Single View App

Introduction 

View
 In this article we will see in detail on how to create our Xamarin Android Single View App. You can develop the Xamarin application as Xamarin.Forms for Cross Platform or you can develop native app for Android and IOS using Xamarin.iOS and Xamarin.Android.In this article we will be see on how to create a native app for Android and here we have selected the Xamarin Android for Single View App. 

In this Mobile App we will see

  •  Display the Current time using TextClock
  •  Create a Notification to display the click Counts
  •   Add a Music (MP3) file to resource
  • Play Song with added MP3 file
  •  Stop the Song
  •  Increase the Mobile Volume
  •  Decrease the Mobile Volume

In this Mobile App we will be adding TextClock to display the current time and five buttons. In the first button click event we will be displaying the notification at the top with count of button click. In second button click event we will play song using the added mp3 from resource. In the third button click we will stop playing the song. In the fourth button click we can increase the volume of the playing song. In the fifth button click we can decrease the volume of sounds.

Prerequisites

Make sure you have installed all the prerequisites in your computer. If not, then download and install all, one by one.

  1. First, download and install Visual Studio 2017 from this link

Make sure you have installed the Mobile development with .NET

Step 1: Create your Xamarin  

After installing our Visual Studio 2017 click Start, then Programs and select Visual Studio 2017 - Click Visual Studio 2017. Click New, then Project, select Visual C# and Android then select Single-View App (Android). Enter your project name and click 

Step 2: Xamarin Android Project Structure 

References:

The References has the default .Net assemblies like System,System.core and for Xamarin Android the most important reference is the Mono.Android ,by default this reference will be added as we can see in the image. This Mono.Android reference will be used to interact with our C# code and Android API’s.

MainActivity:

In our .Net applications by default the Main method will be run and from our application will be start execution but in Android app we have collection of activities and each activity will be used for a single view and when we create the Xamarin Android application is created by default the MainActivity.cs. Here we will be using this activity to run our app. All the activities will be inheriting from the Activity class as when we open the MainActivity.cs file we can see that. From our MainActivity we can set the view which need to be displayed when we run our App. Here we can see by default we can see the Main View has been added to SetContentView.

How to set the default Main Activity when we have multiple Activity?

As we told you that in our Xamarin.Android App we can have multiple Activity and need to have one main Activity to show by default when we run the App. If we have more than one activity and in case if we need to set other activities as the main activity then we can set at the top of activity code as “MainLauncher = true” for that activity and false for other activities.

You can also set the Label(Title) for your app from the Activity ,here we have set the title as “Shanu Music App” and also we can set Icon for the App.

Lifecycle of Activity:

OnCreate() -> When the Activity is created

OnStart() - > When the Activity is started

OnResume() -> Called when Activity will start interacting with user.

OnPause() -> Activity is not visible to user(Working in Background)

OnStop() -> Activity is not available for user

OnDestroy() -> Before the Activity is destroyed

In our demo we have by default the OnCreate() and we will be using this to show our view when the App is running with button click events to perform our needed actions. 

View:

Activity and Views are the important part of Xamarin Android App’s. As we see the Activity is used to show our View and to write code for the events and View is used to design our App. 

Views will be located inside the Resources and Layout Folder We can see by default Main.axml will be added in our layout folder. The view will be as a “axml” file and its purely of XML code.

When we open the Main.axml file we can see the Designer and Source part. We can add controls as drag and drop from Toolbox as per our need and design our Android App. When we click on the Source part we can see the controls added to our App in XML code like below.

Values / Strings.XML

We can see that in our Button text the caption is added as “android:text="@string/hello” and here the “="@string/hello” means that the text will be loaded from the Strings.XML

The string for the hello will be added in the Strings.XMl from the Resources \ Values\

We can change or add the string as per our needs** *** *

Resource.Designer

All the resources like controls we are adding in the View or the text we are adding in the String.XMl file will be generated with unique number in the Resource.Designer file from the solution.  

Hope you have some basic understanding on working with Xamarin Android App and now let’s focus on how to add more controls to make our simple Music App.

Step 3: Working with Code

Displaying Time using TextClock

We will add the TextClock control to our App and design with the below code, here we have set the format as 12 hours and set the font size and color.

<TextClock xmlns:p2="http://xamarin.com/mono/android/designer-default"
        android:format12Hour="hh:mm:ss a"
        android:layout_width="match_parent"
        android:layout_height="47.5dp"
        android:id="@+id/textClock1"
        android:gravity="center_horizontal"
        android:textColor="#ffccff"
        android:textSize="40sp"
        android:layout_marginBottom="4.5dp" />

When we run the application, we can see the output in the emulator as the time will be displayed in our application and the time will be automatically displaying with the current time and second.

Displaying Notification

Now we will add a button and, in the button, click event we will display the notification at the top with the no of time the user clicked on the buttons.

<Button
        android:id="@+id/myButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
       android:background="@android:drawable/alert_dark_frame" />

we need to add the Xamarin.Android.Support v4  package to our APP. Right click the solution and click on Manage NUGet Package and search for Xamarin.Android.Support.v4 and click on install.

In the MainActivity.cs file now we will create the button click event for the above design. First we import the below reference to our MainActivity.cs file

using Android.Support.V4.App; 
using Android.Support.V4.View; 
using Java.Interop; 
using Android.Views.Animations;

In the MainActivity .cs onCreate method we will be create the button click event to display the notification message in our Mobile device.For this we create object for the NotificationCompact and we set the Title and Text for our Notification message and in the Text we also set the counter value to display how many times the button has been clicked from our notification.

Button btn = FindViewById<Button>(Resource.Id.myButton); 
  
            btn.Click += delegate  { 
                var notification = new  NotificationCompat.Builder(this) 
                            .SetContentTitle("Shanu - Notifications") 
                            .SetContentText("Clicked " + count++ + " times!") 
  
                            .SetSmallIcon(Android.Resource.Drawable.DialogFrame) 
                            .SetGroup("testGroup").Build(); 
  
                var manager = NotificationManagerCompat.From(this); 
                manager.Notify(1, notification); 
                btn.Text = "Check Notification!";

Notification Output:

When we run the application, we can see the output in the emulator with the Button.

When we click on the Button we can see the Notification at the top with the count value display as how many time the user clicks on the button.

Playing the Song

First, we add our favorite MP3 songs to our Resource folder and for this simple demo, we have added one mp3 file to be played.

Create the raw Folder


We need to create a folder inside our Resource folder as named as raw and we will be adding all our mp3 files to this folder. To add the mp3 file right click on the raw folder and Add Existing Item and select your mp3 file which need to be played. Here we have added one mp3 file to our raw resource folder.

MediaPlayer mp;

 For adding the MediaPlayer we import the reference as below to our MainActivit.cs file

using Android.Media;

 Now we will add a button and, in the button, click event we will play the music from our newly added mp3 resource file.In our Main.axml file design your button 

<Button
        android:text="Play Song"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:background="@android:drawable/alert_dark_frame" />

Add the button click event for Play Song button from our MainActivity.cs and add the below code to play your music. 

// to Play the Song 
            Button btn1 = FindViewById<Button>(Resource.Id.button1); 
            btn1.Click += delegate
            { 
                mp = MediaPlayer.Create(this, Resource.Raw.Kannalanae); 
                mp.Start(); 
  
                btn1.Text = "Song is Playing Now enjoy :)";  
            };

Play Song Output:

When we run the application, we can see the output from our emulator and we can see the newly added Play Song button in our App.

When the user clicks on the Play Song button they can listen to the songs which they have added.

Stop the Song

For stopping the playing song, we will create a new button and, in the button, click event we will write our code to stop the playing song. 

Now we will add a button and, in the button, click event we will stop the playing music.

In our Main.axml file design your button to stop the music

<Button
        android:text="Stop Song"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:background="@android:drawable/alert_dark_frame" />

Add the button click event for stop the playing song from our MainActivity.cs and add the below code to stop the playing music. 

// to Stop Playing  Song 
            Button btn2 = FindViewById<Button>(Resource.Id.button2); 
            btn2.Click += delegate
            { 
                if (mp != null) 
                    if (mp.IsPlaying) 
                { 
                    mp.Stop(); 
                    btn2.Text = "Song Playing Stopped :( "; 
                } 
                  
            };

Stop Music Output:

When we run the application, we can see the output from our emulator with newly added Stop Song button in our App

When the user clicks on the Stop Song button the playing song will be stopped.

Increase the Volume

For increase the mobile device or emulator volume, we will create a new button and, in the button, click event we will write our code to increase the volume.

Now we will add a button and, in the button, click event we will write code to increase the volume.

In our Main.axml file design your button to increase the volume.

<Button 
        android:text="Volume ++"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button3"
        android:background="@android:drawable/alert_dark_frame" />

Add the button click event to increase the volume from our MainActivity.cs and add the below code to increase the volume. Here we will be use the AudioManager and set the volume as Android.Media.Adjust.Raise

//Increase the Mobile Volume 
            AudioManager audios =    (AudioManager)GetSystemService(Context.AudioService); 
   
            Button btn3 = FindViewById<Button>(Resource.Id.button3); 
            btn3.Click += delegate
            { 
                audios.AdjustStreamVolume(Android.Media.Stream.Music, 
                             Android.Media.Adjust.Raise, Android.Media.VolumeNotificationFlags.PlaySound);  
            };

Volume Increase Output:

When we run the application, we can see the output from our emulator with newly added Volume ++ button in our App we can see the Media volume is set to low now.


When the user clicks on the Volume ++ Button the volume will be slowly increasing and now the Media volume has been set to its maximum sound.

Decrease the Volume

For decrease the mobile device or emulator volume, we will create a new button and, in the button, click event we will write our code to decrease the volume.

Now we will add a button and, in the button, click event we will write code to decrease the volume.

In our Main.axml file design your button to increase the volume

<Button
        android:text="Volume --"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button4"
        android:background="@android:drawable/alert_dark_frame" />

Add the button click event to decrease the volume from our MainActivity.cs and add the below code to decrease the volume. Here we will be use the AudioManager and set the volume as Android.Media.Adjust.Lower

//Decrease the Mobile Volume 
            Button btn4 = FindViewById<Button>(Resource.Id.button4); 
            btn4.Click += delegate
            { 
    audios.AdjustStreamVolume(Android.Media.Stream.Music, 
Android.Media.Adjust.Lower, Android.Media.VolumeNotificationFlags.PlaySound);  
            };

Volume Decrease Output:

When we run the application, we can see the output from our emulator with newly added Volume --button in our App we can see the Media volume is set to high now.

When the user clicks on the Volume -- Button the volume will be slowly decreasing and now the Media volume has been set to its low sound.

Conclusion

Hope you enjoy reading this article ,Download the source code and change as per your need and soon we will see more articles related to developing Xamarin mobile apps.

See Also

Download

Getting started with Xamarin Android Single View App