Create App Using Xamarin.Android Using C# - Part Four

Introduction

Xamarin.Android has native user interface controls. These controls can be easily added to Xamarin.Android apps either using the Android Designer or programmatically via XML layout files. Xamarin.Android exposes all of the user interface object properties and methods in C#.
 
To know more about Xamarin, go to Part-3>>.
 
Description

In this module, I will show you the basic controls in Xamarin and Visual Studio Toolbox mostly used in Xamarin.Android and how to build a sample app.

Download Source Code

Click Here>>

Important Lists Of UI controls

WebView

WebView is a UI element that allows you to create your own window for viewing the web page. Also, you can develop a complete browser.

ViewPager

The ViewPager is a layout manager that allows the user to flip left and right through pages of data.

Toolbar

The Toolbar widget (introduced in Android 5.0 Lollipop) can be thought of as a generalization of the action bar interface – it is intended to replace the action bar. The Toolbar can be used anywhere in an app layout, and it is much more customizable than an action bar. 

TextureView

TextureView is a view that uses hardware-accelerated 2D rendering to enable a video or OpenGL content stream to be displayed. 

Switch

Switch is a UI element that allows a user to toggle between two states, such as ON or OFF. The Switch default value is OFF. 

Spinner

Spinner is a UI element that provides a quick way to select one value from a set. It is similar to a dropdown list. 

AutoComplete

AutoCompleteTextView is an editable text view element that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop-down menu from which the user can choose an item to replace the content of the edit box with. 

Popup Menu

PopupMenu is used for displaying popup menus that are attached to a particular view. 

Pickers

Pickers are UI elements that allow the user to pick a date or a time using dialogs that are provided by Android. 

Navigation Bar

The Navigation Bar provides navigation controls on devices that do not include hardware buttons for Home, Back, and Menu. 

Gallery

Gallery is a layout widget that is used to display items in a horizontally scrolling list; it positions the current selection at the center of the view. 

Edit Text

EditText is a UI element that is used for entering and modifying text. 

CardView

CardView is a UI component that presents text and image content in views that resemble cards. CardView is implemented as a FrameLayout widget with rounded corners and a shadow. Typically, aCardView is used to present a single row item in a ListView or GridView view group. 

Action Bar

ActionBar is a toolbar that displays the activity title, navigation interfaces, and other interactive items. Typically, the action bar appears at the top of an activity's window. 

Calendar

The Calendar class is used for converting a specific instance in time to values such as year, month, hour, a day of the month, and the date of the next week. Calendar supports and provides options with calendar data, including the ability to read and write events, attendees, and reminders. By using the calendar provider in your application, data you add through the API will appear in the built-in calendar app that comes with Android. 

Buttons

Buttons are UI elements that the user taps to perform an action. 

Toolbox In Visual Studio 



Toolbox In Xamarin

 

Let's Create a Basic App

Step-1


Create an Android app project named "SatyaprakashAndroidApp1".

Project Structure

 

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

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 specific subfolders within the resources folder. Notice 6 different Drawable folders which are kept separated based on the DPI displays. These folders 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.

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 Active Life Cycle to effectively handle user data in the changing states such as Running, Paused, Backgrounded & Stopped. For the TripXpense app, I am yet to implement this feature. Here’s an example of an Activity.

All your Activity classes should derive from Activity base class. Notice the MainLauncher = true set of custom attribute – this is to set the starting screen for 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
the SetContentView() >> It places your layout on the screen. Layouts can be accessed using the static variable Resources.Layout.<yourLayoutName>.

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.

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.

Code Ref Main.axml

Open Main.axml in Resources >> Layout folder. 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:minWidth="25px"  
  7.     android:minHeight="25px">  
  8.     <TextView  
  9.         android:text="Small Text"  
  10.         android:textAppearance="?android:attr/textAppearanceSmall"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="wrap_content"  
  13.         android:id="@+id/textView1" />  
  14.     <Button  
  15.         android:text="Click Me"  
  16.         android:layout_width="match_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:id="@+id/button1" />  
  19. </LinearLayout>  
Code Description
 
Here, I have added one Textview and a button. Also, mentioned their IDs.
  1. <TextView    
  2.         android:text="Small Text"    
  3.         android:textAppearance="?android:attr/textAppearanceSmall"    
  4.         android:layout_width="match_parent"    
  5.         android:layout_height="wrap_content"    
  6.         android:id="@+id/textView1" />    
  7.     <Button    
  8.         android:text="Click Me"    
  9.         android:layout_width="match_parent"    
  10.         android:layout_height="wrap_content"    
  11.         android:id="@+id/button1" />    
Here is the code for layout of the page.
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:orientation="vertical"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:minWidth="25px"  
  6.     android:minHeight="25px">  
Code Ref MainActivity.cs
 
It is nothing but the code behind file.
  1. using System;  
  2. using Android.App;  
  3. using Android.Content;  
  4. using Android.Runtime;  
  5. using Android.Views;  
  6. using Android.Widget;  
  7. using Android.OS;  
  8.   
  9. namespace SatyaprakashAndroidApp1  
  10. {  
  11.     [Activity(Label = "SatyaprakashAndroidApp1", MainLauncher = true, Icon = "@drawable/icon")]  
  12.     public class MainActivity : Activity  
  13.     {  
  14.         int count = 1;  
  15.   
  16.         protected override void OnCreate(Bundle bundle)  
  17.   
  18.         {  
  19.   
  20.             base.OnCreate(bundle);  
  21.   
  22.             // Set our view from the "main" layout resource  
  23.   
  24.             SetContentView(Resource.Layout.Main);  
  25.   
  26.             Button btn = FindViewById<Button>(Resource.Id.button1);  
  27.   
  28.             TextView tv = FindViewById<TextView>(Resource.Id.textView1);  
  29.   
  30.             btn.Click += delegate { tv.Text = "Satyaprakash Samantaray First Xamarin Android App"; };  
  31.   
  32.         }  
  33.     }  
  34. }  
Code Description
 
The Following namespace should be added to access the corresponding class file and related methods, properties.
  1. using System;    
  2. using Android.App;    
  3. using Android.Content;    
  4. using Android.Runtime;    
  5. using Android.Views;    
  6. using Android.Widget;    
  7. using Android.OS;  
Here, I have added activity title with the icon image file.
  1. [Activity(Label = "SatyaprakashAndroidApp1", MainLauncher = true, Icon = "@drawable/icon")]  
By default, Android gives your application a title bar when it is run. The value used for this is /manifest/application/activity/@android:label. In most cases, this value will differ from your class name. To specify your app's label on the title bar, use the Label property.
  1. public class MainActivity : Activity  
  2. {  
  3.      
  4. }  
This results in nothing being generated in AndroidManifest.xml. If you want an <activity/> element to be generated, you need to use the [Activity] custom attribute.
 
Note  - The [Activity] attribute has no effect on abstract types; abstract types are ignored.
 
If you wish to override this default and explicitly specify the name of your activity, use the Name property.
  1. [Activity (Name="Satyapprakash.My.activity")]  
  2. public class MyActivity : Activity  
  3. {  
  4. }  
Set Default Activity Among Many Activity
 
By default, your activity will not show up in Android's application launcher screen. This is because there will likely be many activities in your application, and you don't want an icon for everyone. To specify which one should be launchable from the application launcher,
use the MainLauncher property.
  1. [Activity(Label = "SatyaprakashAndroidApp1", MainLauncher = true, Icon = "@drawable/icon")]  
Activity Section Converts Into XML
  1. [Activity(Label = "SatyaprakashAndroidApp1", MainLauncher = true)]  
  2. public class MainActivity : Activity  
  3. {  
  4.   
  5. }  
Converted to XML code.
  1. <activity android:label="SatyaprakashAndroidApp1"   
  2.           android:name="md5a7a3c803e481ad8926683588c7e9031b.MainActivity">  
  3.   <intent-filter>  
  4.     <action android:name="android.intent.action.MAIN" />  
  5.     <category android:name="android.intent.category.LAUNCHER" />  
  6.   </intent-filter>  
  7. </activity>  
Activity Icon

By default, your activity will be given the default launcher icon provided by the system. To use a custom icon, first, add your .png to Resources/drawable, set its Build Action to AndroidResource, then use the Icon property to specify the icon to use.

  1. [Activity(Label = "SatyaprakashAndroidApp1", MainLauncher = true, Icon = "@drawable/icon")]  
Android Manifest Rule
 
When you add permissions to the Android Manifest, these permissions are recorded in Properties/AndroidManifest.xml. For example, if you set the INTERNET permission, the following element is added to Properties/AndroidManifest.xml:  
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="SatyaprakashAndroidApp1.SatyaprakashAndroidApp1" android:versionCode="1" android:versionName="1.0">  
  3.   <uses-sdk android:minSdkVersion="16" />  
  4.   <uses-permission android:name="android.permission.INTERNET" />  
  5.   <application android:label="SatyaprakashAndroidApp1"></application>  
  6. </manifest>  

To edit Android Manifest permissions for your project using Visual Studio -

  1. Right-click on your Android project and select Properties.
  2. Select Android Manifest in the window that opens.
  3. Check the permissions that you want to require in the list of permissions.
You should only request permissions that your application requires to run. Users will be prompted to allow these permissions when they download your application from the Google Play Store.
 
Minimum permissions include
  • INTERNET – for accessing network resources.
  • ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION – for location services.
  • CAMERA – to access the camera.
Other permissions relating to contacts, phone operations, operating system information, time and alarm settings and hardware features.
 
Note

AndroidManifest.xml is generated as part of the build process, and the XML found within Properties/AndroidManifest.xml is merged with XML that is generated from custom attributes. The resulting merged AndroidManifest.xml resides in the obj subdirectory; for example, it resides at obj/Debug/android/AndroidManifest.xml for Debug builds. The merging process is trivial: it uses custom attributes within the code to generate XML elements, and inserts those elements into AndroidManifest.xml.  
 
The Android manifest describes the capabilities of your activity. This is done via Intents and the [IntentFilter] custom attribute. You can mention which actions are appropriate for your activity with the IntentFilter constructor, and which categories are appropriate for the Categories property.
 
Then, I create a method and that should be called when activity will start.
  1. protected override void OnCreate(Bundle bundle)  
  2.       {  
  3.           base.OnCreate(bundle);  
Set our View from the "main" layout resource.
  1. SetContentView(Resource.Layout.Main);  
Then, find the ID of the TextView and button control using FindViewById from the XML Layout Resource.
  1. Button btn = FindViewById<Button>(Resource.Id.button1);  
  2.   
  3. TextView tv = FindViewById<TextView>(Resource.Id.textView1);  
Now, inside button click, I have mentioned local variable of TextView to show the result.
  1. btn.Click += delegate { tv.Text = "Satyaprakash Samantaray First Xamarin Android App"; };  
OUTPUT
 
After button click, the TextView will show the message. 
 
 
 
The file is installed. You can check in App List.
 
 
 
Summary

We have learned the following in this article.
  • UI Controls In Xamarn.Android
  • Basic on AndroidManifest
  • Basic App using Xamarin.Android.
  • Check if your app is installed in App List. 


Similar Articles