Represents a push-button widget. Push-buttons can be pressed, or clicked, by the user to perform an action.
A typical use of a push-button in an activity would be the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
} |
However, instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute. For example:
1 2 3 4 5
| <Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/self_destruct"
android:onClick="selfDestruct" /> |
Now, when a user clicks the button, the Android system calls the activity's selfDestruct(View) method. In order for this to work, the method must be public and accept a View as its only parameter. For example:
1 2 3
| public void selfDestruct(View view) {
// Kabloey
} |
The View passed into the method is a reference to the widget that was clicked.
Partager