
At in Example 1-11, we examine the ID of the View. Remember that each widget has
a unique ID as we define it in the main.xml file. These values are then defined in the
generated R.java class.
At and , if the key event occurred in the Total Amount or No. of People fields, we
check for the value entered in the field. We are ensuring that the user has not left both
fields blank.
At we check if the user has selected the Other radio button, and then we ensure that
the Other text field is not empty. We also check once again if the Total Amount and
No. of People fields are empty.
So the purpose of our KeyListener is now clear: ensure that all text fields are not empty
and only then enable the Calculate button.
Listening to button clicks
Now we will look at the Calculate and Reset buttons. When the user clicks these but-
tons, we use the static interface OnClickListener() which will let us know when a button
is clicked.
As we did with the text fields, we create just one listener and within it we detect which
button was clicked. Depending on the button that was clicked, the calculate() or
reset() method is called.
Example 1-12 shows how the click listener is added to the buttons.
Example 1-12. Code snippet 6 of /src/com/examples/tipcalc/Tipster.java
/* Attach listener to the Calculate and Reset buttons */
btnCalculate.setOnClickListener(mClickListener);
btnReset.setOnClickListener(mClickListener);
Example 1-13 shows how to detect which button is clicked by checking for the ID of
the View that receives the click event.
Example 1-13. Code snippet 7 of /src/com/examples/tipcalc/Tipster.java
/**
* ClickListener for the Calculate and Reset buttons.
* Depending on the button clicked, the corresponding
* method is called.
*/
private OnClickListener mClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnCalculate) {
calculate();
} else {
reset();
}
56 | Chapter 1: Getting Started
Comments to this Manuals