Click here to Skip to main content
14,971,296 members
Articles / Mobile Apps / Xamarin
Article
Posted 1 May 2018

Stats

11.9K views
549 downloads
21 bookmarked

Getting started with Xamarin Android Single View App

Rate me:
Please Sign up or sign in to vote.
4.92/5 (10 votes)
7 May 2018CPOL10 min read
Create Xamarin Android Single View app
In this article, we will see in detail how to create our Xamarin Android Single View App.

Image 1

Introduction

 * Kindly view my Youtube video to learn Getting started with Xamarin Android Single View App.

In this article, we will see in detail 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 see 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 how to:

  • 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

Image 2

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 the 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.

Background

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

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

Make sure you have installed the Mobile development with .NET.

Image 3

Using the Code

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. 

Image 4

Step 2: Xamarin Android Project Structure

Image 5

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 APIs.

MainActivity

Image 6

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 needs 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 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.

Image 7

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 Apps. 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.

Image 8

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

Image 9

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:

Image 10

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.

Image 11

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:

Image 12

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. 

Image 13

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.

XML
<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.

Image 14

Displaying Notification

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

XML
<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.

Image 15

We can see the new Xamarin Android Support DLL has been added to our project.

Image 16

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:

C#
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 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.

C#
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!";

The code will look like this:

Image 17

Notification Output

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

Image 18

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

Image 19

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

Image 20

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 needs to be played. Here, we have added one mp3 file to our raw resource folder.

Image 21

Next, create an object for the MediaPlayer:

C#
MediaPlayer mp;

For adding the MediaPlayer, we import the reference as below to our MainActivity.cs file:

C#
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.

XML
<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. 

C#
// 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.

Image 22

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

Image 23

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.

XML
<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.   

C#
// 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.

Image 24

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

Image 25

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:

XML
<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.

C#
//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.

Image 26

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.

Image 27

Decrease the Volume

For decreasing 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.

XML
<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.

C#
//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.

Image 28

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.

Points of Interest

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.

History

  • 1st May, 2018: Initial version - ShanuSingleViewAPP.zip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionThanks Pin
Member 1035577325-May-20 0:42
MemberMember 1035577325-May-20 0:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.