AND101 Intro to Xamarin.Android

Exercise 3: Implement an Activity's behavior and run your app in an emulator

The goal of this exercise is to write C# code to access and manipulate the UI of an Activity. Your code will need to read/write the properties on several text controls and subscribe to an event on a button. To do this, you will need to assign IDs to some of the views in the XML and lookup the views by ID in the code.

You will be continuing to work on the TipCalculator app. The picture below shows the UI. The two TextViews that display the words "Tip" and "Total" are static and you won't need to access them. All the other views will need to be accessed from code: the EditText so you can read the amount of the bill, the Button so you can subscribe to its Click event, and the other two TextViews so you can display the values you calculate for the tip and total.

Completed Tip Calculator
To complete the exercise, you will need Visual Studio for Windows or macOS with the Xamarin development tools installed. You will also need either an emulator/simulator or a device to run the exercise on. Please see the setup page if you need help installing the Xamarin development environment.

Open the solution

This exercise is a continuation of the previous exercise. You can use your existing solution or begin from the prior Exercise 2 > Completed solution in your copy of the cloned or downloaded course materials.


Add IDs to your views

Here, you will add IDs to several of your UI views so you can access them from code.

  1. Open the file Resource > Layout > Main.axml in the Source view.
  2. Add an ID to the EditText. The XML is shown below. The "@+id" characters indicate that you want to create a new ID value. The text after the forward slash is the value for the ID.
<EditText
  android:id="@+id/inputBill"
  ... />
  1. Add an ID of calculateButton to the Button.
  2. Add an ID of outputTip to the second TextView inside the first of the two horizontal LinearLayouts.
  3. Add an ID of outputTotal to the second TextView inside the second of the two horizontal LinearLayouts.
 <Button
    android:id="@+id/calculateButton"
    ... />

 <TextView
    android:id="@+id/outputTip"
    ... />

<TextView
    android:id="@+id/outputTotal"
    ... />

Look-up views in code

Next, use the IDs to lookup views in code. You will store the references in fields inside your Activity class.

  1. Open MainActivity.cs.
  2. Add four fields to the MainActivity class, one for each of the four views to which you added IDs (i.e. an EditText, a Button, and two TextViews).
EditText inputBill;
Button calculateButton;
TextView outputTip;
TextView outputTotal;
  1. Inside OnCreate, use the FindViewById method to lookup each of the four views and assign the returned references to the corresponding fields. Be sure to place your lookup code after the call to SetContentView; the views you are trying to access are created in SetContentView so they don't exist until after that call completes.
protected override void OnCreate(Bundle bundle)
{
   base.OnCreate(bundle);
   SetContentView(Resource.Layout.Main);

   inputBill = FindViewById<EditText>(Resource.Id.inputBill);
   ...
}
Note: When typing this code by hand, make sure to use the Resource (singular) namespace instead of Resources, or you won't be able to find the Id members for your app.

Subscribe to an event

Recall that we need to respond when the user taps the Calculate button - that will be our signal that the user has entered the amount of their bill and is ready for us to calculate the tip and total.

  1. Inside OnCreate, subscribe a handler to the button's Click event. The Click event uses the standard .NET event pattern so the handler will have an object parameter and an EventArgs parameter.
using System;
...

protected override void OnCreate(Bundle bundle)
{
   ...
   calculateButton = FindViewById<Button>(Resource.Id.calculateButton);
   calculateButton.Click += OnCalculateClick;
}

void OnCalculateClick(object sender, EventArgs e)
{
  ...
}

Retrieve user input

  1. In your handler for the Button's Click event, retrieve the Text from the EditText. This will be the amount of the bill. Store it in a local variable of type string.
  2. Convert the bill input from a string to a double. Store the result in a local variable. You can include error checking if you would like to; however, the solution will omit it in order to keep the code focused on the key techniques.
void OnCalculateClick(object sender, EventArgs e)
{
   string text = inputBill.Text;
   var bill = double.Parse(text);
   ...
}

Compute the results

Continue working in the Click event handler for the Calculate button.

  1. Compute a 15% tip for the bill and store it in a local variable.
  2. Compute the total payment (original bill + tip) and store it in a local variable.
void OnCalculateClick(object sender, EventArgs e)
{
   string text = inputBill.Text;
   var bill = double.Parse(text);

   var tip = bill * 0.15;
   var total = bill + tip;
   ...
}

Display the results

  1. Load the tip amount into the Text property of the TextView intended to display the tip. Your tip amount should be in a variable of type double so you can use its ToString method to convert it into a string so you can assign it to the Text property of the TextView.
  2. Load the total payment into the Text property of the TextView intended to display the total.
void OnCalculateClick(object sender, EventArgs e)
{
    string text = inputBill.Text;
    var bill = double.Parse(text);
    var tip = bill * 0.15;
    var total = bill + tip;

    outputTip.Text = tip.ToString();
    outputTotal.Text = total.ToString();
}

Adjust the margin

Currently, the text labels "Tip" and "Total" do not have any space between them and the result values to their right. You can adjust this by including a layout margin setting on these TextViews. Margin adds space around the outside of a view. There are several options for margin - we will only use the variant that adds space to the right side.

  1. Add the attribute setting shown below to the TextView displaying the text "Tip".
android:layout_marginRight="20dp"
  1. Repeat the previous step for the TextView displaying the text "Total".

Run the app

  1. Run the app to test your work. The image below shows an example of the expected output.
Running the completed Android app

Exercise summary

In this exercise, you implemented the behavior for an Activity. The key technique was assigning IDs to your views in XML and then using the IDs to lookup the views from code. This lets you write code that manipulates your Activity's UI.

You can view the completed solution in the Exercise 3 > Completed folder of your copy of the cloned or downloaded course materials.

Go Back