1  package com.android.pig;
   2  // Pig Latin program for Android, by Bill Rubin
   3  import android.app.Activity;
   4  import android.os.Bundle;
   5  import android.view.View;
   6  import android.view.View.OnClickListener;
   7  import android.widget.Button;
   8  import android.widget.EditText;
   9  import android.widget.TextView;
  10  
  11  public class PigLatin extends Activity implements OnClickListener {
  12      @Override
  13      public void onCreate(Bundle savedInstanceState) {
  14          super.onCreate(savedInstanceState);
  15          setContentView(R.layout.main);
  16  
  17          findViewById(R.id.translate_button).setOnClickListener(this);
  18          findViewById(R.id.clear_button)    .setOnClickListener(this);
  19  
  20          input  = (EditText) findViewById(R.id.input_text);
  21          output = (TextView) findViewById(R.id.output_text);
  22      }
  23  
  24      public void onClick(View v) {
  25        switch(v.getId()) {
  26          case R.id.translate_button: onTranslate(); break;
  27          case R.id.clear_button:     onClear();     break;
  28          default: break;
  29          }
  30      }
  31  
  32      private void onTranslate() {
  33          String in = input.getText().toString();
  34          String[] words = in.split("\\s+");  // Split using white space
  35          String result = "";
  36          String vowels = "aeiou";
  37          for(int i = 0; i<words.length; i++) {  // For each word ...
  38              String word = words[i];
  39              // Split always gives at least one word; begin with white space gives word:
  40              if(word.length()==0) continue;  
  41              if(vowels.contains(word.substring(0,1))) result += word + "-ay ";
  42              else {  // Starts with consonant:
  43                  int prefix;
  44                  if(word.length()>=2 && word.substring(0,2).equals("qu")) prefix = 2;
  45                  else {  // Find first vowel:
  46                      for(prefix = 0; prefix<word.length(); prefix++) 
  47                          if(vowels.contains(word.substring(prefix,prefix+1))) break;
  48                      }
  49                  result += word.substring(prefix) + "-" + word.substring(0,prefix) + "ay ";
  50                  }
  51              }
  52              output.setText(result);            
  53          }
  54  
  55      private void onClear() {
  56          input.setText("");
  57          output.setText("");
  58          }
  59  
  60      private EditText input;
  61      private TextView output;
  62  }