O'Reilly 9781449388416 Datasheet Page 67

  • Download
  • Add to my manuals
  • Print
  • Page
    / 74
  • Table of contents
  • BOOKMARKS
  • Rated. / 5. Based on customer reviews
Page view 66
Example 1-10. Code snippet 4 of /src/com/examples/tipcalc/Tipster.java
/*
* Attach a KeyListener to the Tip Amount, No. of People and Other Tip
* Percentage text fields
*/
txtAmount.setOnKeyListener(mKeyListener);
txtPeople.setOnKeyListener(mKeyListener);
txtTipOther.setOnKeyListener(mKeyListener);
Notice that we create just one listener instead of creating anonymous/inner listeners
for each text field. I am not sure if my style is better or recommended, but I always write
in this style if the listeners are going to perform some common actions. Here the com-
mon concern for all the text fields is that they should not be empty, and only when they
have values should the Calculate button be enabled.
Example 1-11. Code snippet 5 from KeyListener.java
/*
* KeyListener for the Total Amount, No of People and Other Tip Percentage
* text fields. We need to apply this key listener to check for the following
* conditions:
*
* 1) If the user selects Other Tip Percentage, then the Other Tip Percentage text field
* should have a valid tip percentage entered by the user. Enable the
* Calculate button only when the user enters a valid value.
*
* 2) If the user does not enter values in the Total Amount and No. of People fields,
* we cannot perform the calculations. Hence we enable the Calculate button
* only when the user enters valid values.
*/
private OnKeyListener mKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (v.getId()) {
case R.id.txtAmount:
case R.id.txtPeople:
btnCalculate.setEnabled(txtAmount.getText().length() > 0
&& txtPeople.getText().length() > 0);
break;
case R.id.txtTipOther:
btnCalculate.setEnabled(txtAmount.getText().length() > 0
&& txtPeople.getText().length() > 0
&& txtTipOther.getText().length() > 0);
break;
}
return false;
}
};
1.15 Program: Tipster, a Tip Calculator for the Android OS | 55
Page view 66
1 2 ... 62 63 64 65 66 67 68 69 70 71 72 73 74

Comments to this Manuals

No comments