To Lecture Notes

IT 372 -- Apr 24, 2019

Review Exercises

  1. What is a callback method? How does using collback methods illustrate the Hollywood Principle?
    Ans: A callback method is not called by the program, but by the operating system. All of the callback methods we have seen are event handlers, that fire when an event triggers them. For example, the CLICK event triggers the OnClick event handler. The Hollywood Principle says "Don't call us, we'll call you." In other words the Android operating system says "Don't call the callback method from your program, let the operating system call your callback method when the corresponding event occurs."
  2. In the TempConverter Project, what are three ways to set up an onClick event handler? Ans:
    1. Set an onClick attribute in the widget that will cause the event handler to fire.
    2. Add an inner class to the Activity class that implements the View.OnClickListener interface. This object is attached to the widget using the setOnClickListener method.
    3. Add an anonymous inner class that implements the View.OnClickListener interface, which is attached to the widget using the setOnClickListener method.
  3. Suppose that I is an interface whose required method is f with signature ( ) and return value void. Show how to instantiate an object from an anonymous class that implements I. Ans:
    // --- I.java: Interface source code:
    public interface I {
        public void f( );
    }
    
    // --- Main.java: source code for testing
    public class Main {
        public static void main(String[ ] args) {
            I obj = new I( ) {
                System.out.println("Running overloaded f method of I.");
            };
            obj.f( );
        }
    }
    
  4. Display a toast at the bottom of the layout. A toast is text that is temporarily displayed in the layout, usually near the bottom.
    Ans: Add an onClick attribute to the LinearLayout and this event handler in the MainActivity.java code:
    protected void onClick(View view) {
        CharSequence text = "Hello, I'm a toast.";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(this, text, duration);
        toast.show( );
    }
    

More Android Widgets

Stopwatch Example

Array Adapters