Home > Xamarin Android Application Development

Xamarin Android Application Development

Page 1

Page 2
Xamarin Android Application Development
Diptimaya Patra
This book is for sale at http://leanpub.com/xamarin-android-app-dev This version was published on 2014-03-16 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. ©2013 - 2014 Diptimaya Patra

Page 3
Tweet This Book!
Please help Diptimaya Patra by spreading the word about this book on Twitter! The suggested hashtag for this book is #XamarinAndroidBookDPatra. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter:
https://twitter.com/search?q=#XamarinAndroidBookDPatra

Page 4
Contents
Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Linear Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Relative Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Table Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Frame Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Using Android Styles in Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 ListView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Binding Data to ListView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Display Entity Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Selective ListView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Get Selected Items from ListView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 ListView in a ScrollView Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Selective ListActivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Selective ListActivity with Entity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Context Menu in ListView Item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Displaying selective Image in ListView . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Dialogs and Toast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Alert Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Date Picker Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Time Picker Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Toast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

Page 5
Layout
Layout in android is a View group type, which can contain views inside it. So basically it is a container, based on requirement. Anything that can be a view can be a child of Layout. A custom layout could also be created for custom requirement, as the Layouts are derived from ViewGroup class. There are few types of Layouts available in Android, we would discuss all. 1. Linear Layout 2. Relative Layout 3. Table Layout 4. Frame Layout
Linear Layout
A Linear Layout could have children displaying either in horizontal or in vertical. Let’s have a layout example we would do for all the above layouts. We would have two EditText controls with describing TextView and a Button control to do something. Linear Layout – Horizontal As discussed above, a Linear Layout with orientation set as horizontal; places children views in horizontal order. Such as following.

Page 6
Layout
2 The XML layout would be as below. As you see in the above layout XML, Linear Layout has a property as Layout_Height as wrap_- content. Basically we have four types by which we could set the width or height of the ViewGroup or the View. 1. Fill Parent – Fills the parent

Page 7
Layout
3 2. Wrap Content – Wraps with the maximum allowed (Parent’s) width or height 3. Match Parent – Same as Fill Parent but added with different OS version 4. Unit Values 5. DP – Density independent Pixels, based on physical density of the screen. 6. SP – Scale independent Pixels, scaled by user’s font size. Recommended to use with fonts. 7. DPI – Same as DP 8. PX – Pixels, corresponds to actual pixels on the screen. 9. IN – Inches, based on the physical size of the screen. 10. MM – Millimetres, based on the physical size of the screen. 11. PT – Points, 1/72 of the inch based on the physical size of the screen. If we add few more buttons to the above layout, it would not scroll and the height would wrap. For the above layout, we have 8 buttons; but displayed 5 buttons, also we cannot scroll. We would see later, how to add scrolling to the layout. Linear Layout – Vertical A Linear Layout with orientation set as vertical; places children views in vertical order. Such as following:

Page 8
Layout
4 As you see in above image, the buttons are having Layout_Width property as Wrap_Content; that is the reason buttons are wrapped wherever content is finished. Let’s add few more buttons and with different Layout_Width setting. If you look at above Layout and it’s button’s Layout_Width property changes with respect to the content; you would understand it properly. These properties are common property for View or ViewGroup. Now a Vertical Linear Layout cannot scroll it’s content automatically. As mentioned earlier, we would discuss it in later chapter.

Page 9
Layout
5
Relative Layout
A Relative Layout has always relationship with its children. You can also say that, children of Relative Layout are related to layout. This is one of the complicated layouts you would ever see. The reason is too many properties to set for child and parent to get what we want. The following are the properties. 1. Relative to Parent Container 2. Layout_AlignParentBottom – displays child at bottom of parent 3. Layout_AlignParentLeft – displays child on the left side of the parent 4. Layout_AlignParentRight – displays child on the right side of the parent 5. Layout_AlignParentTop – displays child at the top of the parent 6. Layout_CenterHorizontal – centers the child horizontally in the parent 7. Layout_CenterInParent – centers the child both horizontally and vertically in the parent 8. Layout_CenterVertical – centers the child vertically in the parent 9. Relative to Other View 10. Layout_Above – places the child above the view 11. Layout_Below – places the child below the view 12. Layout_ToLeftOf – places the element left of the view 13. Layout_ToRightOf – places the element right of the view 14. Align with Other View 15. Layout_AlignBaseline – aligns baseline of the new view with the baseline of specified view 16. Layout_AlignBottom – aligns bottom of the new view with the bottom of the specified view 17. Layout_AlignLeft – aligns left of the new view with the left of the specified view 18. Layout_AlignRight – aligns right of the new view with the right of the specified view 19. Layout_AlignTop – aligns top of the new view with the top of the specified view The following is a simple example where, a SeekBar control’s current Progress property would be displayed on the right side.

Page 10
Layout
6 This would look similar to the following in design view. As it is a complex layout to describe, we would use it wherever it’s useful and we would discuss the layout there.
Table Layout
This is one of the most used Layouts. As the name says the View is organised in Rows and Columns. However to have columns in the Row, we need to use a Table Row, which would contain the children. The number of children present in a TableRow, is exactly the number of Columns present in the Row.

Page 11
Layout
7 Also, it’s not obvious that; the number of columns present in first row would be same in the following Row. That’s the poor thing about it; each row’s column count is dependent on its children count. The following design is made using a Table Layout. The above example shows that we can place elements in virtual columns. This is calculated based on the space available with respect to the maximum column assigned +1. So if we are assigning Layout_Column as 1 then it would be a 3 column row. Now adjust the above view to look decent. The following changes are made.

Page 12
Layout
8 The StretchColumns property of the Table itself fixed the first two rows. Likewise we would be discussing more about these properties while we progress in this book.
Frame Layout
Each child view in Frame Layout starts from the Top Left of the Layout.

Page 13
Layout
9 As you see in the above design, the ImageView and TextView are layered one after another. So basically, each starts displaying from the top left of the parent layout. It’s up to the designer to design it.
Using Android Styles in Layout
Android has also some inbuilt styles for Layouts. In some design scenarios, where we would require a fixed layout at the bottom of the screen. The fixed layout may contain a set of controls. In this post, we would see how we do that. Here is a sample layout with LinearLayout (above the last LinearLayout).

Page 14
Layout
10 As you see in above image, the last control before the Fixed Layout, should have the above properties with values. Now, the Linear Layout would become fixed at the bottom, once you apply the style of ButtonBar. Now the Button inside it is the content of the fixed layout.
Conclusion
We have discussed the Layouts in Xamarin Android development. If you are a designer, you should be able to mix and match the Layouts to provide the perfect required design. Keep designing.

Page 15
ListView
ListView is a ViewGroup that displays a list of items that could be scrollable. We had an interaction with a ListView using the ListActivity. We would see few more things about ListView in this chapter.
Binding Data to ListView
Previously we had an encounter with ListActivity which had a ListView, and we used a ListActivity for displaying data or collection. Here we would use theListView control and bind data or collection to it. We would need a template for the ListView, so let’s add one. Add an XML file to the Layout folder.

Page 16
ListView
12 Add a TextView in the XML file. This is for ListView template. And as you see in the below image, the Activity1 is inherited from Activity class unlike our last post where we inherited from ListActivity. Rest of the code is self-explanatory. We are setting the Adapter property of the ListView with ArrayAdapter. Now, let’s run the application and see the ListActivity in action.

Page 17
ListView
13 As you see, unlike ListActivity, we have other controls in the Activity.
Display Entity Collection
In real time, we would be displaying a collection of entity. Here, we would display a collection of some entity in ListView. Let’s start with creating the following Person entity. The Person entity class is located under Model.

Page 18
ListView
14 Now let’s add the ListView template XML file under Layout folder. Keep a TextView for now inside the XML file.

Page 19
ListView
15 Add a ListView control to the Main Layout. The following method would generate sample data. Now in Activity1, we would get the ListView control and set the data by using following code. Let’s run the application. Oops, the entity class name is displayed instead of data. That means we

Page 20
ListView
16 need to do a different way to display data. Not so difficult, just create another class which wouldbe derived fromthe abstract class BaseAdapter. The following properties and methods are implemented once you inherit the class. The following modifications are done to the class, which is self-explanatory.

Page 21
ListView
17 And back to Activity1, and do the following for displaying data in ListView. Well, it has displayed with a single TextView inside the template.

Page 22
ListView
18 How about displaying Email Id below the Full Name. This will require a change in the ListViewTem- plate1 change. Following are the changes. And in the Screen Adapter class, GetView would be changed like this.

Page 23
ListView
19 Now run the application, and you would see the Email Id is also displayed. As you see a in the above output, two TextView controls are displayed.
Selective ListView
Here we would see how to display a collection in ListView and select one or many items. As we are going to have a ListView, the following is the simple layout.

Page 24
ListView
20 Now instead of creating a layout for the ListView content, we would use some from the An- droid.Resource . And adding the ChoiceMode property to the ListView. Here is the view, with single selection mode with Radio Buttons.

Page 25
ListView
21 We have a CheckBox style instead of RadioButton, here are the changes. And you would get the Check image instead of the RadioButton.

Page 26
ListView
22 Now, let’s try for the multiple selections. Also you need to change the ChoiceMode to Multiple. And you would get the multiple checked items.

Page 27
ListView
23 The choice modes are clearly useful for having single or multiple choice interactions from user.
Get Selected Items from ListView
Previously we had seen to display a list where user could select single or multiple. Here we would see, how to get the selected items from the screen activity where a list of options are displayed. The following is the layout for displaying the Multiple Selectable ListView with a button.

Page 28
ListView
24 Now we would bind data to the ListView. Also we would make it Multiple Selectable with SelectOption as Multiple. And we would subscribe to the click event of the Button. In the button click event handler, we would do as following to get the selected data out of ListView.

Page 29
ListView
25 ShowAlert is a helper method to show alerts with easy, here is the code for that too. Now run the application. You could see the fixed. As on button click, the selected items positions with respect to the collection is displayed.

Page 30
ListView
26 The selected items are displayed in the alert dialog, but you might find out that, even if a selection is made and reverted back; the item’s state was registered as false or true. In that case we need to check based on the true values in the collection.
ListView in a ScrollView Issue
In Windows Phone application development, use of ListBox and ScrollViewer have no issues in scrolling the content. But in Android using both are not advisable. They might behave differently. Here we would explore that, and find out how we try to fix this.

Page 31
ListView
27 The above layout consists of a ScrollView as the parent ViewGroup, which has two elements in it. A TextView and a ListView. For the issue to happen, we would have some long text in the TextView. Now we would bind data to the Adapter of the ListView so that data would be displayed. Now let’s run the application.

Page 32
ListView
28 As you see in the above output, the TextView is scrolled to the end, and the ListVIew is partially displayed. To confirm that, you also notice that, we have a scrollbar scrolled to the end of the view. Also the bottom reached orange display is displayed. Enough confirmation, now to fix that we need a method which does the following. As you see in the above method, individually takes the item from the adapter and adds to the total. And finally it assigns to the height of the ViewGroup.

Page 33
ListView
29 To use the above method, we need to call it, just after you assign adapter of the ListView. Now, the above output looks fixed. The ScrollBar is still in the middle, that means we have some items to display from the ListView. A quick note though, this has been tested with Android 4.0 and above, the results were successful.
Selective ListActivity
In Activity chapter, we had a glance to look at the ListActivity, also in this chapter we have seen a selective ListView. Now we would combine it and provide a selective ListActivity.

Page 34
ListView
30 As you see in the above code display, we are assigning the ArrayAdapter to the ListAdapter property of the ListActivity class. It has also the property for ChoiceMode. You could assign your required choice mode and it would work like ListView. The above output shows the implementation of selective in the ListActivity.
Selective ListActivity with Entity
Previously, we have seen that, binding a string array to the ListAdapter and displaying data. If you have an entity collection, how do we bind? Consider WeekdayItem is the entity.

Page 35
ListView
31 As you see in the above class, it has two properties Id and Name. Now we would have a sample collection of WeekdayItem as List

Page 36
ListView
32 It is derived from BaseAdapter abstract class. Now in the GetView overridden method, we are finding the TextView and displaying the day name. Notice that we have used an Android Resource Layout. And to find out the TextView inside it we are using the Resource Id Text1.

Page 37
ListView
33 In the above output, the entity collection is successfully displayed in the ListActivity.
Context Menu in ListView Item
Here, we would see how we add context menu to the ListView Item. Let’s have the layout like below. In the above layout, we have taken ListView to display the data.

Page 38
ListView
34 Now, let’s have a file collection and display it in the ListView. Also we would call RegisterForCon- textMenu method which takes the ListView. We need to override the OnCreateContextMenu method and add the menu items and also the title of the context menu. As we are having the files displayed, let’s have a menu for file operations.

Page 39
ListView
35 Now, the above output is for displaying file names in the ListView. Now, Tap and Hold; then the context menu would be displayed like above.

Page 40
ListView
36 To know which context menu item you have selected; you could use the above code to find it out. Get ListView Item with Context menu selection Also to operate on the ListView item on context menu selection is required.

Page 41
ListView
37 Intheabovecodedisplay,theIMenuItemtypeistypecastedtoAdapterView.AdapterContextMenuInfo. This would give us the position of the item in the Adapter. Which we could find out in our code.
Displaying selective Image in ListView
The above output shows that, the Temp.data file was tapped to display the context menu. And the copy menu was selected from the context menu. The dialog box confirms that. In some scenarios, you need to display a image (change the image source) based on some value. For example stock prices go up, then up arrow; and when coming down, down arrow image. Here we would follow up on our previous example.

Page 42
ListView
38 As you see in the above FileItem entity class a bool IsUpdated property is present. As the name suggests it determines whether the file is synced or not. Let’s have the above ListView layout. Also we require an item template for the ListView. The above layout shows that, we have an ImageView and a TextView in the template.

Page 43
ListView
39 In the above GetView method from the custom adapter class, finding out the TextView and assigns the text to it. Also the ImageView’s image is changed. Assume that you have added two different images for the flag display. The Resource is set by using the SetImageResource method. The above output consists of the selective image display based on the condition check.
Conclusion
In this chapter we have seen ListVIew specifically. Different scenarios with ListView were presented with their solution approach.

Page 44
Dialogs and Toast
A dialog is a small window that is prompted to the user to make a decision or enter additional information. We have 3 types of dialogs defined in Android system.
Alert Dialog
This is a type of dialog, where content is displayed with a dialog title and a button. The following layout is for the example of displaying alert dialogs. We have three buttons. The following code is very simple; we are getting the controls from the layout and subscribing to the respective click events. Single Button Alert Dialog In the following example the basic single button dialog is displayed.

Page 45
Dialogs and Toast
41 As you see in the above code snippet, we are creating a builder. The builder is assigned to AlertDialog object. Then we are setting Title, Icon, and Message. Also we are setting the button OK. A single button is mandatory for displaying dialogs. Now, subscribing to the click event if you need to do something here. Two Buttons Alert Dialog The following code snippet is for creating two buttons in Alert Dialog. As you see in the below code snippet; we are setting buttons using SetButton and SetButton2. This is same as first button; the second button is considered here as Negative and the first as positive. Three Buttons Alert Dialog The following code snippet would help you understand creating three buttons in Alert Dialog. From previous code, we have added another SetButton3. Here the SetButton is considered as positive, SetButton3 as negative and the SetButton2 as neutral.

Page 46
Dialogs and Toast
42 Let’s run the application and you would see the first screen where all three buttons are there. Let’s click the first button.

Page 47
Dialogs and Toast
43 A simple alert dialog with a Title, Message and a button is displayed. Now clicking the second button.

Page 48
Dialogs and Toast
44 An icon is displayed with the title; also we have two buttons displayed. This dialog could be used for confirmations. And finally we would click on the third button.

Page 49
Dialogs and Toast
45 Three buttons are displayed here; this is where you would take user’s interaction properly.
Date Picker Dialog
We have a DatePickerDialog, which would help to pick a date. The following example would help you how we use it.

Page 50
Dialogs and Toast
46 As you see in the above code, we are declaring a DateTime, a TextView and an Int variable. Then the button’s click event is subscribed. In the button click event handler we are calling the method ShowDialog which takes the int value. The int value is here to distinguish a dialog from each other; in case you have more than one dialog. In the above code snippet; we are overriding OnCreateDialog method from the Activity class. It takes the integer Id as parameter. As we discussed previously there could be multiple dialogs in a single activity; so we would be using a switch case scenario. Also we are creating a new dialog of type DatePickerDialog. The DatePickerDialog takes the context, the event handler on set, the year, the month and the day as parameters. You might notice that, the month is subtracted by 1; this is because you don’t subscribe it by 1, the next month would be displayed. It might be from Android itself. We would run the application and click on the button.

Page 51
Dialogs and Toast
47 The date picker dialog is displayed. You could select the date and click on set to set the date and click on cancel to cancel this operation.

Page 52
Dialogs and Toast
48 On set click the date is set to the text view.

Page 53
Dialogs and Toast
49
Time Picker Dialog
TimePickerDialog is almost similar in using as using DatePickerDialog. The following example would help you using it. As you see below; we have a button and a TextView in the layout. The button is to bring up the dialog and text view is where the value would be set. Now similar to the Previous DatePickerDialog example, we would have an integer variable for Id, an integer variable for hour and one for minute, then TextView variable. Instead of taking hour

Page 54
Dialogs and Toast
50 and minute as integer variables; you could take a TimeSpan variable and use the Hour and Minute properties from it. As you see in the above code, the hour and minute are set to current hour and minute values. Also in the button’s click event we are calling the method ShowDialog, to show the dialog with the id. As we discussed previously, we are having the overridden method OnCreateDialog from Activity class where Id is the parameter for identifying dialogs in the activity. And on TimePickerDataSet handler we are setting the selected values. Let’s run the application.

Page 55
Dialogs and Toast
51 On click of the button, the following Timer Picker dialog is displayed. You notice that the AM/PM changer is also available. This is because we had set the final parameter in creating the TimePickerDialog object. The final parameter is for identifying the 24 hour format or 12 hour format.

Page 56
Dialogs and Toast
52 On setting the time the value is set in the handler; where the values are taken from the TimeSetEven- tArgs.

Page 57
Dialogs and Toast
53
Toast
A toast is a simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout. We have seen dialogs which take user interaction, but in case of toasts user interaction is not needed. For example: you have created some task successfully and you want to notify the user that it’s a success. The following example would help you to use it. As you see in the above code snippet; familiar code is written where two buttons are extracted from the layout and the respective click events are subscribed.

Page 58
Dialogs and Toast
54 As you see in the above code snippet; two toasts are displayed; the first toast is of short length and the second is longer in length. Let’s run the application. On click of the specific buttons the short and long toast is displayed.

Page 59
Dialogs and Toast
55

Page 60
Dialogs and Toast
56
Conclusion
In this chapter we have seen that dialogs are used for getting some interaction from the user. The simple alert dialog could be used for displaying messages. Toasts should be used in case you are doing some operation and user waits whether it’s a success or failure.
Search more related documents:Xamarin Android Application Development

Set Home | Add to Favorites

All Rights Reserved Powered by Free Document Search and Download

Copyright © 2011
This site does not host pdf,doc,ppt,xls,rtf,txt files all document are the property of their respective owners. complaint#nuokui.com
TOP