Xamarin – Quick Guide

Xamarin – Quick Guide ”; Previous Next Xamarin – Installation Xamarin is built on the .NET Framework. It allows one to create apps that easily run across multiple platforms. In this tutorial, we will explain how you can use Xamarin to deliver native iOS, Android, and Windows Apps. Let’s start the tutorial with a discussion on how to install Xamarin in Windows and Mac systems. System Requirements Windows A computer with at least 2GB of RAM and running Windows 7 or higher (Windows 8-10 is highly recommended) Visual Studio 2012 Professional or higher Xamarin for Visual Studio Mac A Mac computer running OS X Yosemite (10.10) or higher Xamarin iOS SDK Apple’s Xcode (7+) IDE and iOS SDK Xamarin Studio Installation on Windows Download the Xamarin Installer from https://www.xamarin.com/download Before running the Xamarin installer, make sure you have installed Android SDK and Java SDK on your computer. Run the downloaded installer to begin the installation process − The Xamarin license agreement screen appears. Click the Next button to accept the agreement. The installer will search for any missing components and prompt you to download and install them. After the Xamarin installation is complete, click the Close button to exit and get ready to start using Xamarin. Installation on Mac Download the Xamarin Studio Installer on your Mac system. Run the Xamarin installer you downloaded and follow the steps given in the Installation Wizard. After the installation is complete, you can start using Xamarin on your system. Xamarin – First Application In this chapter, we will see how to create a small Android application using Xamarin. Hello Xamarin! Application First of all, start a new instance of Visual Studio and go to File → New → Project. On the Menu dialog box that appears, go to Templates → Visual C# → Android → Blank App (Android). Give an appropriate name for your application. In our case, we name it “helloWorld” and save it in the default location provided. Next, click the OK button for the new “helloXamarin” project to load. On the solution, open Resources → layout → Main.axml file. Switch from Design View and go to the Source file and type the following lines of code to build your app. <?xml version = “1.0” encoding = “utf-8”?> <LinearLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:orientation = “vertical” android:background = “#d3d3d3” android:layout_width = “fill_parent” android:layout_height = “fill_parent”> <TextView android:text = “@string/HelloXamarin” android:textAppearance = “?android:attr/textAppearanceLarge” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/textView2” android:textColor = “@android:color/black” /> </LinearLayout> In the above code, we have created a new Android textview. Next, open the folder values and double-click Strings.xml to open it. Here, we are going to store information and values about the button created above. <?xml version = “1.0” encoding = “utf-8”?> <resources> <string name = “HelloXamarin”>Hello World, I am Xamarin!</string> <string name = “ApplicationName”>helloWorld</string> </resources> Open MainActivity.cs file and replace the existing code with the following lines of code. using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace HelloXamarin { public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); } } } Save the application. Build and then run it to display the created app in an Android Emulator. If you do not have an Android Emulator, then follow the steps given in the next section to create one. Setting Up an Android Emulator On your Visual Studio menu, go to Tools → Android → Android Emulator Manager. On the pop-up window that appears, click the Create button. It will display the following screen. On the above screen, supply the AVD name you want. Select a device that is appropriate for your display, e.g., Nexus 4” display. Select your target platform. It is always advisable to test on a minimum target platform, e.g., API 10 Android 2.3 (Gingerbread) so as to ensure your App works across all Android platforms. Fill in the rest of the fields and click the OK button. Your emulator is now ready. You can select it from the list of existing Android Virtual Devices and then click Start to launch it. Modifying HelloXamarin App In this section, we will modify our project and create a button which will display text upon click. Open main.axml and switch to source view. After our textview that we created, we will add a button as shown below. <Button android:id = “@+id/MyButton” android:layout_width = “fill_parent” android:layout_height = “wrap_content” android:text = “@string/ButtonClick” /> After adding a button, our full code will look 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”> <TextView android:text = “@string/HelloXamarin” android:textAppearance = “?android:attr/textAppearanceLarge” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/textView2” /> <Button android:id = “@+id/MyButton” android:layout_width = “fill_parent” android:layout_height = “wrap_content” android:text = “@string/ButtonClick” /> </LinearLayout> Next, we register our button values in the strings.xml file. <string name = “ButtonClick”>Click Me!</string> After adding our button in the strings.xml file, we will open MainActivity.cs file to add an action for our button when it is clicked, as shown in the following code. using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace HelloXamarin { [Activity(Label = “HelloXamarin”, MainLauncher = true, Icon = “@drawable/icon”)] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); Button button = FindViewById<Button>(Resource.Id.MyButton); button.Click += delegate { button.Text = “Hello world I am your first App”; }; } } } Next, build and run your application. After clicking on the button, you will get the following output − Xamarin – Application Manifest All Android Apps have a manifest file commonly referred to as AndroidManifest.xml. The manifest file contains everything about the Android platform that an App needs in order to run successfully. Here, we have listed down some of the important functions of a manifest file − It declares the minimum API level required by the application. It declares the permissions required by the application, e.g., camera, location,

Xamarin – Installation

Xamarin – Installation ”; Previous Next Xamarin is built on the .NET Framework. It allows one to create apps that easily run across multiple platforms. In this tutorial, we will explain how you can use Xamarin to deliver native iOS, Android, and Windows Apps. Let’s start the tutorial with a discussion on how to install Xamarin in Windows and Mac systems. System Requirements Windows A computer with at least 2GB of RAM and running Windows 7 or higher (Windows 8-10 is highly recommended) Visual Studio 2012 Professional or higher Xamarin for Visual Studio Mac A Mac computer running OS X Yosemite (10.10) or higher Xamarin iOS SDK Apple’s Xcode (7+) IDE and iOS SDK Xamarin Studio Installation on Windows Download the Xamarin Installer from https://www.xamarin.com/download Before running the Xamarin installer, make sure you have installed Android SDK and Java SDK on your computer. Run the downloaded installer to begin the installation process − The Xamarin license agreement screen appears. Click the Next button to accept the agreement. The installer will search for any missing components and prompt you to download and install them. After the Xamarin installation is complete, click the Close button to exit and get ready to start using Xamarin. Installation on Mac Download the Xamarin Studio Installer on your Mac system. Run the Xamarin installer you downloaded and follow the steps given in the Installation Wizard. After the installation is complete, you can start using Xamarin on your system. Print Page Previous Next Advertisements ”;

Xamarin – Building the App GUI

Xamarin – Building the App GUI ”; Previous Next TextView TextView is a very important component of the Android widgets. It is primarily used for displaying texts on an Android screen. To create a textview, simply open main.axml and add the following code between the linear layout tags. <TextView android:text = “Hello I am a text View” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/textview1” /> Button A button is a control used to trigger an event when it is clicked. Under your Main.axml file, type the following code to create a button. <Button android:id = “@+id/MyButton” android:layout_width = “fill_parent” android:layout_height = “wrap_content” android:text = “@string/Hello” /> Open ResourcesValuesStrings.xml and type the following line of code in between <resources> tag. <string name=”Hello”>Click Me!</string> The above code provides the value of the button we created. Next, we open MainActivity.cs and create the action to be performed when the button is clicked. Type the following code under base.OnCreate (bundle) method. Button button = FindViewById<Button>(Resource.Id.MyButton); button.Click += delegate { button.Text = “You clicked me”; }; The above code displays “You Clicked Me” when a user clicks on the button. FindViewById<< –> This method finds the ID of a view that was identified. It searches for the id in the .axml layout file. Checkbox A checkbox is used when one wants to select more than one option from a group of options. In this example, we are going to create a checkbox which on selected, displays a message that it has been checked, else it displays unchecked. To start with, we open Main.axml file in our project and type the following line of code to create a checkbox. <?xml version = “1.0” encoding = “utf-8”?> <LinearLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:orientation = “vertical” android:background = “#d3d3d3” android:layout_width = “fill_parent” android:layout_height = “fill_parent”> <CheckBox android:text = “CheckBox” android:padding = “25dp” android:layout_width = “300dp” android:layout_height = “wrap_content” android:id = “@+id/checkBox1” android:textColor = “@android:color/black” android:background = “@android:color/holo_blue_dark” /> </LinearLayout> Next, go to MainActivity.cs to add the functionality code. CheckBox checkMe = FindViewById<CheckBox>(Resource.Id.checkBox1); checkMe.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { CheckBox check = (CheckBox)sender; if(check.Checked) { check.Text = “Checkbox has been checked”; } else { check.Text = “Checkbox has not been checked”; } }; From the above code, we first find the checkbox using findViewById. Next, we create a handler method for our checkbox and in our handler, we create an if else statement which displays a message depending on the outcome selected. CompoundButton.CheckedChangeEventArgs → This method fires an event when the checkbox state changes. Progress Bar A progress bar is a control that is used to show the progression of an operation. To add a progress bar, add the following line of code in Main.axml file. <ProgressBar style=”?android:attr/progressBarStyleHorizontal” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/progressBar1” /> Next, go to MainActivity.cs and set the value of the progress bar. ProgressBar pb = FindViewById<ProgressBar>(Resource.Id.progressBar1); pb.Progress = 35; In the above code, we have created a progress bar with a value of 35. Radio Buttons This is an Android widget which allows a person to choose one from a set of options. In this section, we are going to create a radio group containing a list of cars which will retrieve a checked radio button. First, we add a radio group and a textview as shown in the following code − <?xml version = “1.0” encoding = “utf-8”?> <LinearLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:orientation = “vertical” android:background = “@android:color/darker_gray” android:layout_width = “fill_parent” android:layout_height = “fill_parent”> <TextView android:text = “What is your favourite Car” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/textView1” android:textColor = “@android:color/black” /> <RadioGroup android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/radioGroup1” android:backgroundTint = “#a52a2aff” android:background = “@android:color/holo_green_dark”> <RadioButton android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:text = “Ferrari” android:id = “@+id/radioFerrari” /> <RadioButton android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:text = “Mercedes” android:id = “@+id/radioMercedes” /> <RadioButton android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:text = “Lamborghini” android:id = “@+id/radioLamborghini” /> <RadioButton android:text = “Audi” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/radioAudi” /> </RadioGroup> </LinearLayout> To perform an action, when a radio button is clicked, we add an activity. Go to MainActivity.cs and create a new event handler as shown below. private void onClickRadioButton(object sender, EventArgs e) { RadioButton cars = (RadioButton)sender; Toast.MakeText(this, cars.Text, ToastLength.Short).Show (); } Toast.MakeText() → This is a view method used to display a message/output in a small pop up. At the bottom of the OnCreate() method just after SetContentView(), add the following piece of code. This will capture each of the radio buttons and add them to the event handler we created. RadioButton radio_Ferrari = FindViewById<RadioButton> (Resource.Id.radioFerrari); RadioButton radio_Mercedes = FindViewById<RadioButton> (Resource.Id.radioMercedes); RadioButton radio_Lambo = FindViewById<RadioButton> (Resource.Id.radioLamborghini); RadioButton radio_Audi = FindViewById<RadioButton> (Resource.Id.radioAudi); radio_Ferrari.Click += onClickRadioButton; radio_Mercedes.Click += onClickRadioButton; radio_Lambo.Click += onClickRadioButton; radio_Audi.Click += onClickRadioButton; Now, run your application. It should display the following screen as the output − Toggle Buttons Toggle button are used to alternate between two states, e.g., it can toggle between ON and OFF. Open ResourceslayoutMain.axml and add the following lines of code to create a toggle button. <?xml version = “1.0” encoding = “utf-8”?> <LinearLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:orientation = “vertical” android:background = “#d3d3d3” android:layout_width = “fill_parent” android:layout_height = “fill_parent”> <ToggleButton android:id = “@+id/togglebutton” android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:textOn = “Torch ON” android:textOff = “Torch OFF” android:textColor = “@android:color/black” /> </LinearLayout> We can add actions to the toggle bar when it is clicked. Open MainActivity.cs and add the following lines of code after the OnCreate() method class. ToggleButton togglebutton = FindViewById<ToggleButton> (Resource.Id.togglebutton); togglebutton.Click += (o, e) => { if (togglebutton.Checked) Toast.MakeText(this, “Torch is ON”, ToastLength.Short).Show (); else Toast.MakeText(this, “Torch is OFF”, ToastLength.Short).Show(); }; Now, when you run the App, it should display the following output − Ratings Bar A Ratings Bar is a form element that is made up of stars which app users can use to rate things you have provided for them. In your Main.axml file, create a new rating bar with 5 stars. <?xml version

Xamarin – Application Manifest

Xamarin – Application Manifest ”; Previous Next All Android Apps have a manifest file commonly referred to as AndroidManifest.xml. The manifest file contains everything about the Android platform that an App needs in order to run successfully. Here, we have listed down some of the important functions of a manifest file − It declares the minimum API level required by the application. It declares the permissions required by the application, e.g., camera, location, etc. It gives permissions to hardware and software features used or required by the application. It lists the libraries that the application must be linked. The following screenshot shows a Manifest file. Application name − It refers to the title of your App Package name − It is an unique name used to identify your App. Application Icon − It is the icon displayed on the Android home screen for your App. Version Number − It is a single number that is used to show one version of your App is more recent than another. <manifest xmlns:android=”http://schemas.android.com/apk/res/android” android:versionCode=”1″ > Version Name − It is a user-friendly version string for your App that users will see on your App settings and on the Google PlayStore. The following code shows an example of a version name. <manifest xmlns:android=”http://schemas.android.com/apk/res/android” android:versionName=”1.0.0″> Minimum Android Version − It is the lowest Android version platform which your application supports. <uses-sdk android:minSdkVersion=”16″ /> In the above example, our minimum Android version is API Level 16, commonly referred to as JELLY BEAN. Target Android Version − It is the Android version on which your App is compiled against. Print Page Previous Next Advertisements ”;

Xamarin – First Application

Xamarin – First Application ”; Previous Next In this chapter, we will see how to create a small Android application using Xamarin. Hello Xamarin! Application First of all, start a new instance of Visual Studio and go to File → New → Project. On the Menu dialog box that appears, go to Templates → Visual C# → Android → Blank App (Android). Give an appropriate name for your application. In our case, we name it “helloWorld” and save it in the default location provided. Next, click the OK button for the new “helloXamarin” project to load. On the solution, open Resources → layout → Main.axml file. Switch from Design View and go to the Source file and type the following lines of code to build your app. <?xml version = “1.0” encoding = “utf-8”?> <LinearLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:orientation = “vertical” android:background = “#d3d3d3” android:layout_width = “fill_parent” android:layout_height = “fill_parent”> <TextView android:text = “@string/HelloXamarin” android:textAppearance = “?android:attr/textAppearanceLarge” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/textView2” android:textColor = “@android:color/black” /> </LinearLayout> In the above code, we have created a new Android textview. Next, open the folder values and double-click Strings.xml to open it. Here, we are going to store information and values about the button created above. <?xml version = “1.0” encoding = “utf-8”?> <resources> <string name = “HelloXamarin”>Hello World, I am Xamarin!</string> <string name = “ApplicationName”>helloWorld</string> </resources> Open MainActivity.cs file and replace the existing code with the following lines of code. using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace HelloXamarin { public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); } } } Save the application. Build and then run it to display the created app in an Android Emulator. If you do not have an Android Emulator, then follow the steps given in the next section to create one. Setting Up an Android Emulator On your Visual Studio menu, go to Tools → Android → Android Emulator Manager. On the pop-up window that appears, click the Create button. It will display the following screen. On the above screen, supply the AVD name you want. Select a device that is appropriate for your display, e.g., Nexus 4” display. Select your target platform. It is always advisable to test on a minimum target platform, e.g., API 10 Android 2.3 (Gingerbread) so as to ensure your App works across all Android platforms. Fill in the rest of the fields and click the OK button. Your emulator is now ready. You can select it from the list of existing Android Virtual Devices and then click Start to launch it. Modifying HelloXamarin App In this section, we will modify our project and create a button which will display text upon click. Open main.axml and switch to source view. After our textview that we created, we will add a button as shown below. <Button android:id = “@+id/MyButton” android:layout_width = “fill_parent” android:layout_height = “wrap_content” android:text = “@string/ButtonClick” /> After adding a button, our full code will look 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”> <TextView android:text = “@string/HelloXamarin” android:textAppearance = “?android:attr/textAppearanceLarge” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/textView2” /> <Button android:id = “@+id/MyButton” android:layout_width = “fill_parent” android:layout_height = “wrap_content” android:text = “@string/ButtonClick” /> </LinearLayout> Next, we register our button values in the strings.xml file. <string name = “ButtonClick”>Click Me!</string> After adding our button in the strings.xml file, we will open MainActivity.cs file to add an action for our button when it is clicked, as shown in the following code. using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace HelloXamarin { [Activity(Label = “HelloXamarin”, MainLauncher = true, Icon = “@drawable/icon”)] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); Button button = FindViewById<Button>(Resource.Id.MyButton); button.Click += delegate { button.Text = “Hello world I am your first App”; }; } } } Next, build and run your application. After clicking on the button, you will get the following output − Print Page Previous Next Advertisements ”;

Xamarin – Permissions

Xamarin – Permissions ”; Previous Next In Android, by default, no application has permissions to perform any operations that would have an effect on the user or the operating system. In order for an App to perform a task, it must declare the permissions. The App cannot perform the task until the permission are granted by the Android system. This mechanism of permissions stops applications from doing as they wish without the user’s consent. Permissions are to be recorded in AndroidManifest.xml file. To add permissions, we double-click on properties, then go to Android ManRequired permissions will appear. Check the appropriate permissions you wish to add. Camera − It provides permission to access the device’s camera. <uses-permission android:name=”android.permission.CAMERA” /> Internet − It provides access to network resources. <uses-permission android:name=”android.permission.INTERNET” /> ReadContacts − It provides access to read the contacts on your device. <uses-permission android:name=”android.permission.READ_CONTACTS” /> ReadExternalStorage − It provides access to read and store data on an external storage. <uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” /> Calendars − It allows an app access to the calendar on the user device and events. This permission can be dangerous, as it grants an app the ability to send emails to guests without the owner’s awareness. The syntax for adding this permission is as shown below − <uses-permission android:name=”android.permission-group.CALENADAR” /> SMS − An app with this permission has the ability to use the devices messaging services. It includes reading, writing, and editing SMS and MMS messages. Its syntax is as shown below. <uses-permission android:name=”android.permission-group.SMS” /> Location − An app with this permission can access the device’s location using the GPS network. <uses-permission android:name=”android.permission-group.LOCATION” /> Bluetooth − An app with this permission can exchange data files with other Bluetooth enabled devices wirelessly. <uses-permission android:name=”android.permission.BLUETOOTH” /> Print Page Previous Next Advertisements ”;

Xamarin – Layouts

Xamarin – Layouts ”; Previous Next Linear Layout In linear layout, the contents are arranged in either horizontal or vertical manner. Linear Layout ─ Horizontal The contents of this layout are arranged horizontally. For this demo, we are going to create 3 buttons and arrange them horizontally in a linear layout. <?xml version = “1.0” encoding = “utf-8”?> <LinearLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:orientation = “horizontal” android:layout_width = “fill_parent” android:layout_height = “fill_parent” android:background = “#d3d3d3″ android:minWidth=”25px” android:minHeight=”25px”> <Button android:id=”@+id/MyButton1″ android:layout_width=”wrap_content” android:layout_margin=”10dp” android:layout_height=”wrap_content” android:text=”Button 1″ android:background=”@android:color/holo_green_dark” /> <Button android:id=”@+id/MyButton2″ android:layout_width=”wrap_content” android:layout_margin=”10dp” android:layout_height=”wrap_content” android:text=”Button 2″ android:background=”@android:color/holo_green_dark” /> <Button android:id=”@+id/MyButton3″ android:layout_width=”wrap_content” android:layout_margin=”10dp” android:layout_height=”wrap_content” android:text=”Button 3″ android:background=”@android:color/holo_green_dark” /> </LinearLayout> The resulting output is as shown below − Linear Layout ─ Vertical This type of layout places the child view in a vertical manner. <?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” android:background = “#d3d3d3” android:minWidth = “25px” android:minHeight = “25px”> <Button android:id = “@+id/MyButton1” android:layout_width = “fill_parent” android:layout_margin = “10dp” android:layout_height = “wrap_content” android:text = “Button 1” android:background = “@android:color/holo_green_dark” /> <Button android:id = “@+id/MyButton2” android:layout_width = “fill_parent” android:layout_margin = “10dp” android:layout_height = “wrap_content” android:text = “Button 2” android:background = “@android:color/holo_green_dark” /> <Button android:id = “@+id/MyButton3” android:layout_width = “fill_parent” android:layout_margin = “10dp” android:layout_height = “wrap_content” android:text=”Button 3″ android:background = “@android:color/holo_green_dark” /> </LinearLayout> Its resulting output is as follows − Relative Layout In this view, the position of the child view is relative to its parent or to its sibling view. In the following example, we are going to create 3 EditText views and a button and then, align them relatively. Create a new project and call it relative layout app. Open main.axml and add the following code. <?xml version = “1.0” encoding = “utf-8”?> <RelativeLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:layout_width = “match_parent” android:layout_height = “match_parent” android:paddingLeft = “16dp” android:background = “#d3d3d3” android:paddingRight = “16dp”> <EditText android:id = “@+id/name” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:hint = “First Name” android:textColorHint = “@android:color/background_dark” android:textColor = “@android:color/background_dark” /> <EditText android:id = “@+id/lastName” android:layout_width = “0dp” android:layout_height = “wrap_content” android:hint = “Last Name” android:layout_below = “@id/name” android:textColorHint = “@android:color/background_dark” android:textColor = “@android:color/background_dark” android:layout_alignParentLeft = “true” android:layout_toLeftOf = “@+id/age” /> <EditText android:id = “@id/age” android:layout_width = “80dp” android:layout_height = “wrap_content” android:layout_below = “@id/name” android:hint = “Age” android:textColorHint = “@android:color/background_dark” android:textColor = “@android:color/background_dark” android:layout_alignParentRight = “true” /> <Button android:layout_width = “85dp” android:layout_height = “wrap_content” android:layout_below = “@id/age” android:layout_alignParentRight = “true” android:text = “Submit” android:background = “@android:color/holo_green_dark” /> </RelativeLayout> The important parameters that we have used in this code are − android:layout_below − It aligns the child view element below its parent. android:layout_alignParentLeft − It aligns the parent element to the left. android:layout_toLeftOf − This property aligns an element to the left of another element. android:layout_alignParentRight − It aligns the parent to the right. When you build and run the App now, it would produce the following output screen − Frame Layout The frame layout is used to display only one item. It’s difficult to arrange multiple items in this layout without having them overlap each other. Start a new project and call it frameLayoutApp. Create a new Frame Layout as shown below. <?xml version = “1.0” encoding = “utf-8”?> <FrameLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:layout_width = “fill_parent” android:layout_height = “fill_parent”> <ImageView android:id = “@+id/ImageView1” android:scaleType = “matrix” android:layout_height = “fill_parent” android:layout_width = “fill_parent” android:src = “@drawable/img1” /> <TextView android:layout_width = “fill_parent” android:layout_height = “wrap_content” android:textSize = “50dp” android:textColor = “#000” android:text = “This is a Lake” /> <TextView android:gravity = “right” android:layout_width = “fill_parent” android:layout_height = “wrap_content” android:textSize = “50dp” android:text = “A very Deep Lake” android:layout_gravity = “bottom” android:textColor = “#fff” /> </FrameLayout> The above code creates an imageView which fills the entire screen. Two textviews then float above the imageView. Now, build and run your application. It will display the following output − Table Layout In this layout, the view is arranged into rows and columns. Let’s see how it works. <?xml version = “1.0” encoding = “utf-8”?> <TableLayout xmlns:android = “http://schemas.android.com/apk/res/android” android:layout_width = “fill_parent” android:background = “#d3d3d3” android:layout_height = “fill_parent” android:stretchColumns = “1”> <TableRow> <TextView android:text = “First Name:” android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:textColor = “@android:color/black” /> <EditText android:width = “100px” android:layout_width = “fill_parent” android:layout_height = “30dp” android:textColor = “@android:color/black” /> </TableRow> <TableRow> <TextView android:text = “Last Name:” android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:textColor = “@android:color/black” /> <EditText android:width = “50px” android:layout_width = “fill_parent” android:layout_height = “30dp” android:textColor = “@android:color/black” /> </TableRow> <TableRow> <TextView android:text = “Residence:” android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:textColor = “@android:color/black” /> <EditText android:width = “100px” android:layout_width = “fill_parent” android:layout_height = “30dp” android:textColor = “@android:color/black” /> </TableRow> <TableRow> <TextView android:text = “Occupation:” android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:textColor = “@android:color/black” /> <EditText android:width = “100px” android:layout_width = “fill_parent” android:layout_height = “30dp” android:textColor = “@android:color/black” /> </TableRow> <TableRow> <Button android:text = “Cancel” android:layout_width = “wrap_content” android:layout_margin = “10dp” android:layout_height = “wrap_content” android:background = “@android:color/holo_green_dark” /> <Button android:text = “Submit” android:width = “100px” android:layout_margin = “10dp” android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:background = “@android:color/holo_green_dark” /> </TableRow> </TableLayout> The above code creates a simple data entry form arranged using tables and rows. Print Page Previous Next Advertisements ”;

Xamarin – Multiscreen App

Xamarin – Multiscreen App ”; Previous Next In this chapter, we are going to create a login system that enables a user to register. Then, we will take the registered user to the home screen of our App upon successful login. First of all, create a new project and call it Login System. On your new project, go to main.axml and add two buttons and a progress bar as shown below. <?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” android:background = “@android:color/background_light” android:weightSum = “100” android:minWidth = “25px” android:minHeight = “25px”> <TextView android:text = “Login App” android:textAppearance = “?android:attr/textAppearanceMedium” android:layout_width = “match_parent” android:layout_weight = “20” android:layout_height = “0dp” android:textColor = “#368DEB” android:id = “@+id/txtCreatAccount” android:gravity = “center” android:textStyle = “bold” android:textSize = “25sp” /> <Button android:text = “Sign In” android:layout_width = “match_parent” android:layout_weight = “15” android:layout_height = “0dp” android:background = “@drawable/btnSignInStyle” android:id = “@+id/btnSignIn” android:layout_marginLeft = “20dp” android:layout_marginRight = “20dp” android:textSize = “15sp” /> <Button android:text = “Sign Up” android:layout_width = “match_parent” android:layout_weight = “15” android:layout_height = “0dp” android:background = “@drawable/btnSignUpStyle” android:id = “@+id/btnSignUp” android:layout_marginLeft = “20dp” android:layout_marginRight = “20dp” android:textSize = “15sp” /> <RelativeLayout android:layout_width = “match_parent” android:layout_height = “0dp” android:layout_weight = “50” android:minWidth = “25px” android:minHeight = “25px”> <ProgressBar android:layout_width = “wrap_content” android:layout_height = “wrap_content” android:id = “@+id/progressBar1” android:background = “@drawable/progressBarStyle” android:layout_centerInParent=”true” android:indeterminate = “true” xmlns:tools = ” http://schemas.android.com/tools” tools:visibility = “invisible” /> </RelativeLayout> </LinearLayout> After creating the user interface, it’s important to style the buttons to make them look more attractive. To do this, create a new XML file under drawable folder and name the file as btnSignInStyle.xml. In the XML file, add the following lines of code − <selector xmlns:android = “http://schemas.android.com/apk/res/android”> <item android:state_pressed = “false”> <layer-list> <item android:right = “5dp” android:top = “5dp”> <shape> <corners android:radius = “2dp”/> <solid android:color = “#D6D6D6″/> </shape> </item> <item android:left = “2dp” android:bottom = “2dp”> <shape> <corners android:radius = “4dp”/> <gradient android:angle = “270” android:endColor = “#486EA9” android:startColor = “#486EA9″/> <stroke android:width = “1dp” android:color = “#BABABA”/> <padding android:bottom = “10dp” android:right = “10dp” android:left = “10dp” android:top = “10dp”/> </shape> </item> </layer-list> </item> <item android:state_pressed = “true”> <layer-list> <item android:right = “5dp” android:top = “5dp”> <shape> <corners android:radius = “2dp”/> <solid android:color = “#D6D6D6″/> </shape> </item> <item android:left = “2dp” android:bottom = “2dp”> <shape> <corners android:radius = “4dp”/> <gradient android:angle = “270” android:endColor = “#79C791” android:startColor = “#486EA9″/> <stroke android:radius = “4dp” android:color = “#BABABA”/> <padding android:bottom = “10dp” android:right = “10dp” android:left = “10dp” android:top = “10dp”/> </shape> </item> </layer-list> </item> </selector> The above code sets the colors of the button on load and on click, it also sets the border radius of the button. Next, we create a similar styling XML as above for the signup button. To do this, create another XML under drawable folder and call it btnSignUpStyle.xml. It will inherit everything from btnSignInStyle.xml. The only difference will be the buttons’ gradient start and end color. Change the startColor and endColor in btnSignUpStyle.xml to <gradient android:angle=”270″ android:endColor=”#008000” android:startColor=”#008000″/> Go to layout folder and create a new AXML file and call it registerDailog.axml. This file will contain registration details for new users in our app. The page will contain three EditTexts and a button to submit the data. Add the following code inside your linear layout code. <EditText android:layout_width = “match_parent” android:layout_marginBottom = “10dp” android:layout_marginTop = “25dp” android:layout_marginRight = “25dp” android:layout_marginLeft = “25dp” android:layout_height = “35dp” android:paddingLeft = “10dp” android:id = “@+id/txtUsername” android:hint = “Username” android:textColor = “#000” /> <EditText android:layout_width = “match_parent” android:layout_height = “35dp” android:id = “@+id/txtEmail” android:layout_marginBottom = “10dp” android:layout_marginTop = “25dp” android:layout_marginRight = “25dp” android:layout_marginLeft = “25dp” android:paddingLeft = “10dp” android:textColor = “#000” android:hint = “Email” /> <EditText android:layout_width = “match_parent” android:layout_height = “35dp” android:layout_marginBottom = “10dp” android:layout_marginTop = “25dp” android:layout_marginRight = “25dp” android:layout_marginLeft = “25dp” android:paddingLeft = “10dp” android:textColor = “#000” android:id = “@+id/txtPassword” android:hint = “Password” /> <Button android:text = “Sign Up” android:layout_width = “match_parent” android:layout_height = “wrap_content” android:id = “@+id/btnSave” android:textSize = “20dp” android:textColor = “#fff” android:textStyle = “bold” android:height = “70dp” android:background = “@drawable/btnSignUpStyle” android:paddingLeft = “5dp” android:paddingRight = “5dp” android:paddingTop = “5dp” android:paddingBottom = “5dp” android:layout_marginLeft = “25dp” android:layout_marginRight = “25dp” android:layout_centerHorizontal = “true” /> Next, add a new class called signUpDialog.cs. This class will contain the code required to create a dialog box. The following example shows the code. public class OnSignUpEvent:EventArgs { private string myUserName; private string myEmail; private string myPassword; public string UserName { get { return myUserName; } set{ myUserName = value; } } public string Email { get { return myEmail; } set { myEmail = value; } } public string Password { get { return myPassword; } set { myPassword = value; } } public OnSignUpEvent(string username, string email, string password):base() { UserName = username; Email = email; Password = password; } class SignUpDialog:DialogFragment { private EditText txtUsername; private EditText txtEmail; private EditText txtPassword; private Button btnSaveSignUp; public event EventHandler<OnSignUpEvent> onSignUpComplete; public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { base.OnCreateView(inflater, container, savedInstanceState); var view = inflater.Inflate(Resource.Layout.registerDialog, container, false); txtUsername = view.FindViewById<EditText>(Resource.Id.txtUsername); txtEmail = view.FindViewById<EditText>(Resource.Id.txtEmail); txtPassword = view.FindViewById<EditText>(Resource.Id.txtPassword); btnSaveSignUp = view.FindViewById<Button>(Resource.Id.btnSave); btnSaveSignUp.Click += btnSaveSignUp_Click; return view; } void btnSaveSignUp_Click(object sender, EventArgs e) { onSignUpComplete.Invoke(this, new OnSignUpEvent(txtUsername.Text, txtEmail.Text, txtPassword.Text)); this.Dismiss(); } } } In the above code, we have used the get and set properties. The get method returns a variable, while the set method assigns a value to the returned variable. Here is an example − public string Color { get { return color; } set { color = value; } } In our previous example, we created a method that overrides a view. Inside the method, we created a var called view which referenced to a registerDialog.axml contained in the layout folder. Next, go to mainActivity.cs to create the dialog fragment. private Button signUp; private Button submitNewUser; private EditText txtUsername; private EditText txtEmail; private EditText txtPassword; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); signUp = FindViewById<Button>(Resource.Id.btnSignUp); submitNewUser = FindViewById<Button>(Resource.Id.btnSave); txtUsername =

Xamarin – Andriod Views

Xamarin – Andriod Views ”; Previous Next ListViews A Listview is a user interface element that displays lists of items that are scrollable. Binding data to listviews In this example, you are going to create a listView that displays the days of the week. To start with, let us create a new XML file and name it listViewTemplate.xml. In listViewTemplate.xml, we add a new textview as shown below. <?xml version = “1.0” encoding = “utf-8” ?> <TextView xmlns:android = “http://schemas.android.com/apk/res/android” android:id = “@+id/textItem” android:textSize =”20sp” android:layout_width = “fill_parent” android:layout_height = “wrap_content”/> Next, go to Main.axml and create a new listview inside the Linear Layout. <ListView android:minWidth=”25px” android:minHeight=”25px” android:layout_width=”match_parent” android:layout_height=”match_parent” android:id=”@+id/listView1″ /> Open MainActivity.cs and type the following code to bind the data to the listview we created. The code must be written inside the OnCreate() method. SetContentView(Resource.Layout.Main); var listView = FindViewById<ListView>(Resource.Id.listView1); var data = new string[] { “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” }; listView.Adapter = new ArrayAdapter(this, Resource.Layout.ListViewTemplate, data); Var data = new string[] simply holds our items as an array. Array Adapter returns the items in our collection as a view. By default, the Array Adapter uses a default textView to display each item. In the above code, we created our own textview in ListViewTemplate.xml and referenced it using the constructor shown below. ArrayAdapter(this, Resource.Layout.ListViewTemplate, data); Finally, build and run your application to view the output. GridViews A gridView is a view group that allows applications to lay out content in a two-dimensional way, scrollable grid. To add a GridView, create a new project and call it gridViewApp. Go to Main.axml and add a grid as shown below. <?xml version = “1.0” encoding=”utf-8″?> <GridView xmlns:android = “http://schemas.android.com/apk/res/android” android:id = “@+id/gridview” android:layout_width = “fill_parent” android:layout_height = “fill_parent” android:columnWidth = “90dp” android:numColumns = “auto_fit” android:verticalSpacing = “10dp” android:horizontalSpacing = “10dp” android:stretchMode = “columnWidth” android:gravity = “center” /> Next, create a new class and name it ImageAdpter.cs. This class will contain the adapter classes for all items which will be shown in the grid. Inside ImageAdapter, add the following code − public class ImageAdapter : BaseAdapter { Context context; public ImageAdapter(Context ch) { context = ch; } public override int Count { get { return cars.Length; } } public override long GetItemId(int position) { return 0; } public override Java.Lang.Object GetItem(int position) { return null; } public override View GetView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(context); imageView.LayoutParameters = new GridView.LayoutParams(100, 100); imageView.SetScaleType(ImageView.ScaleType.CenterCrop); imageView.SetPadding(8, 8, 8, 8); } else { imageView = (ImageView)convertView; } imageView.SetImageResource(cars[position]); return imageView; } int[] cars = { Resource.Drawable.img1, Resource.Drawable.img2, Resource.Drawable.img3, Resource.Drawable.img4, Resource.Drawable.img5, Resource.Drawable.img6, }; } In the above code, we have simply bound our car images to the image adapters. Next, open MainActivity.cs and add the following code after setContentView(). var gridview = FindViewById<GridView>(Resource.Id.gridview); gridview.Adapter = new ImageAdapter(this); gridview.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs args) { Toast.MakeText(this, args.Position.ToString(), ToastLength.Short).Show(); }; The above code finds the gridView in main.axml and binds it to the imageAdapter class. Gridview.ItemClick creates an onClick event which returns the position of the selected image when a user clicks on an image. Now, build and run your application to view the output. Print Page Previous Next Advertisements ”;