ITEEDU

Listening for UI Notifications

Some UI notifications are automatically exposed and called by Android. For instance, Activity exposes overrideable methods onKeyDown and onKeyUp, and Widget exposes onFocusChanged(boolean, int, Rect). However, some important callbacks, such as button clicks, are not exposed natively, and must be registered for manually, as shown here.

public class SendResult extends Activity
{
    /**
     * Initialization of the Screen after it is first created.  Must at least
     * call setContentView() to
     * describe what is to be displayed in the screen.
     */
    protected void onCreate(Bundle savedValues)
    {
        ...

        // Listen for button clicks.
        Button button = (Button)findViewById(R.id.corky);
        button.setOnClickListener(mCorkyListener);
    }

    // Create an anonymous class to act as a button click listener.
    private OnClickListener mCorkyListener = new OnClickListener()
    {
        public void onClick(View v)
        {
            // To send a result, simply call setResult() before your
            // activity is finished, building an Intent with the data
            // you wish to send.
            Intent data = new Intent();
            data.setAction("Corky!");
            setResult(RESULT_OK, data);
            finish();
        }
    };