Code example for EditText

Methods: setGravitysetInputTypesetTextsetTextSize, setOnFocusChangeListener, setOnKeyListener

  private void initValueEditText( Context context, float initialValue){
    value = initialValue;
    valueText = new EditText( context );
    // Since we're a number that gets affected by the button, we need to be 
    // ready to change the numeric value with a simple ++/--, so whenever 
    // the value is changed with a keyboard, convert that text value to a 
    // number. We can set the text area to only allow numeric input, but 
    // even so, a carriage return can get hacked through. To prevent this 
    // little quirk from causing a crash, store the value of the internal 
    // number before attempting to parse the changed value in the text area 
    // so we can revert to that in case the text change causes an invalid 
    // number 
    valueText.setOnKeyListener(new View.OnKeyListener() {
      public boolean onKey(View v, int arg1, KeyEvent event) {
        float backupValue = value;
        try { 
          value = Float.parseFloat( ((EditText)v).getText().toString() );
        } catch( NumberFormatException nfe ){
          value = backupValue;
        return false; 
    // Highlight the number when we get focus 
    valueText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      public void onFocusChange(View v, boolean hasFocus) {
        if( hasFocus ){
    valueText.setGravity( Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL );
    valueText.setText( value.toString() );
    valueText.setInputType( InputType.TYPE_CLASS_NUMBER );
  private void initDecrementButton( Context context){
    decrement = new Button( context );
    decrement.setTextSize( mTextSize );