Exemples de code Android

Bouton à plusieurs images

Cet exemple présente les deux types de boutons avec image(s). Le premier type fait appel à une seule image. Si celle-ci a un arrière-plan transparent, Android fera varier la couleur de ce dernier selon l'état du bouton : normal, avec attention ("focused") ou cliqué ("pressed").

Le second type de bouton utilise trois images pour correspondre aux trois états possibles. Ces trois images sont spécifiées dans un fichier XML conservé dans le répertoire "res/layout". Pour les deux types de boutons, les images doivent être de format "bmp", "gif", "jpeg" ou "png" et être stockée dans le répertoire "res/drawable".

MainActivity.java

Aucune modification nécessaire au fichier généré par Android Studio.

activity_main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/btn_unique"
        android:src="@drawable/little_red_button"
        android:layout_width="200dp"
        android:layout_height="200dp" />

    <ImageButton
        android:id="@+id/btn_multiple"
        android:src="@drawable/bouton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

bouton.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/clique" /> <!-- pressed -->
    <item android:state_focused="true"
        android:drawable="@drawable/attention" /> <!-- focused -->
    <item android:drawable="@drawable/normal" /> <!-- default -->
</selector>

res/drawable/little_red_button.png
res/drawable/normal.png
res/drawable/attention.png
res/drawable/clique.png