Monday, March 5, 2012

Background Color Changer (Part 2)

This second part of the tutorial will cover adding the code to make this app function properly

Open MainActivity.java and edit the code as follows:


package com.example.bgcolorchanger;


import android.app.Activity;
import android.graphics.Color; //1.
import android.os.Bundle;
import android.view.View; //2.
import android.view.View.OnClickListener; //3.
import android.widget.*; //4.


public class MainActivity extends Activity {
    
  //5.
  //Create fields for the Views in the app
  private LinearLayout container;
  private EditText inputField;
  private Button submitButton;

  //6.
  //Create an OnClickListener that changes the background
  // based on the text in the input field
  private OnClickListener sumbit_text = new OnClickListener() {

    //When the button is clicked, if the input field's text matches
    // one of the color keywords, change the background color to
    // the corresponding color, otherwise, set the background to black
    public void onClick(View view) {
      if (inputField.getText().toString().equalsIgnoreCase("red"))
        container.setBackgroundColor(Color.RED);
      else if (inputField.getText().toString().equalsIgnoreCase("green"))
        container.setBackgroundColor(Color.GREEN);
      else if (inputField.getText().toString().equalsIgnoreCase("blue"))
container.setBackgroundColor(Color.BLUE);
      else if (inputField.getText().toString().equalsIgnoreCase("cyan"))
container.setBackgroundColor(Color.CYAN);
      else if (inputField.getText().toString().equalsIgnoreCase("magenta"))
        container.setBackgroundColor(Color.MAGENTA);
      else if (inputField.getText().toString().equalsIgnoreCase("yellow"))
container.setBackgroundColor(Color.YELLOW);
      else
container.setBackgroundColor(Color.BLACK);
    }
  };

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
        
    //7.
    //Find references for the views by their IDs
    container = (LinearLayout)findViewById(R.id.container);
    inputField = (EditText)findViewById(R.id.inputField);
    submitButton = (Button)findViewById(R.id.submitButton);
        
    //8.
    //Add the onClick listener to the submit button
    submitButton.setOnClickListener(sumbit_text);
  }
}

The code is explained as follows:
  1. For the Color Class 
  2. For the View Class 
  3. For the OnClickListener Class 
  4. For various subclasses of type View 
  5. Create private fields for each object in the layout
  6. Create an OnClickListener for the submit button
  7. Retrieve the references to the objects from the R.java file
  8. Attach the OnClickListener to the submit button so it will execute when the button is pressed

No comments:

Post a Comment