Gérer les clics sur les boutons
L'exemple suivant montre comment il est possible de gérer les clics sur les boutons à l'aide de méthodes individuelles (une par bouton) ou de méthodes partagées.
MainActivity.java
package com.prog101.boutons;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// gère uniquement les clics sur le bouton 1
public void gererBouton1(View vue) {
Toast.makeText(this, "Je suis le bouton 1", Toast.LENGTH_SHORT).show();
}
// gère uniquement les clics sur le bouton 2
public void gererBouton2(View vue) {
Toast.makeText(this, "Je suis le bouton 2", Toast.LENGTH_SHORT).show();
}
// gère les clics sur plusieurs boutons (boutons 3 et 4)
public void gererBouton(View vue) {
Button bouton = (Button)vue;
CharSequence texte = "Je suis le " + bouton.getText();
Toast.makeText(this, texte, Toast.LENGTH_SHORT).show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bouton 1"
android:onClick="gererBouton1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bouton 2"
android:onClick="gererBouton2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bouton 3"
android:onClick="gererBouton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bouton 4"
android:onClick="gererBouton" />
</LinearLayout>