Dec 16, 2010

Handle UI Event -- Event Listeners

Supported Event Listeners


onClick(): View.OnClickListener
onLongClick(): View.OnLongClickListener
onFocusChange(): View.OnFocusChangeListener
onKey(): View.OnKeyListener
onTouch(): View.OnTouchListener
onCreateContextMenu():View.OnCreateContextMenuListener.


Implement Method 1

// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
    }
};
protected void onCreate(Bundle savedValues) {
    ...
    // Capture our button from layout
    Button button = (Button)findViewById(R.id.corky);
    // Register the onClick listener with the implementation above
    button.setOnClickListener(mCorkyListener);
    ...
}

Implement Method 2

public class ExampleActivity extends Activity implements OnClickListener {
    protected void onCreate(Bundle savedValues) {
        ...
        Button button = (Button)findViewById(R.id.corky);
        button.setOnClickListener(this);
    }

    // Implement the OnClickListener callback
    public void onClick(View v) {
      // do something when the button is clicked
    }
    ...
}


No comments: