198 votes

Comment créer un tableau avec des bordures dans Android ?

J'utilise une mise en page de tableau pour afficher les données sous forme de tableau, mais je veux un tableau avec des colonnes et des lignes définies par l'utilisateur avec des bordures. Des suggestions ?

201voto

David Jesse Points 1255

La solution que j'ai trouvée pour ce problème est de placer une ressource xml dessinable dans le champ d'arrière-plan de chaque cellule. De cette manière, vous pourriez définir une forme avec la bordure que vous souhaitez pour toutes les cellules. Le seul inconvénient est que les bordures des cellules extrêmes ont la moitié de la largeur des autres mais ce n'est pas un problème si votre tableau remplit tout l'écran.

Un exemple :

drawable/cell_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape= "rectangle"  >
        <solid android:color="#000"/>
        <stroke android:width="1dp"  android:color="#ff9"/>
</shape>

layout/mon_tableau.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TableRow
        android:id="@+id/tabla_cabecera"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></TableRow>

    <TableLayout
        android:id="@+id/tabla_cuerpo"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>
        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/cell_shape"
                android:padding="5dp"
                android:text="TextView"
                android:textAppearance="?android:attr/textAppearanceMedium"></TextView>

        </TableRow>
    </TableLayout>

</LinearLayout>

Edit : Un exemple

enter image description here

Edit2 : Un autre exemple (avec plus d'éléments : coins de cercle, gradients...) enter image description here

J'ai expliqué ce problème avec plus de détails dans http://blog.intelligenia.com/2012/02/programacion-movil-en-Android.html#more . C'est en espagnol mais il y a des codes et des images de tableaux plus complexes.

0 votes

C'était très utile. Merci pour cet article.

6 votes

Je ne parviens pas à afficher le contenu

1 votes

Comment puis-je définir l'arrière-plan de la vue de manière programmatique ? view.setBackground(?)

56voto

Shawn Points 1407

Je suis d'accord avec Brad. C'était une réponse affreuse. La documentation Android indique que les conteneurs TableLayout n'affichent pas les lignes de bordure, donc les envoyer sur le site Android ne les aidera pas du tout. J'ai pu trouver une solution "sale" sur droidnova, qui consiste à définir une couleur de fond pour le TableLayout, puis à définir une couleur de fond différente pour le TableRow et à ajouter layout_margin à la ligne. Je n'aime pas trop cette solution, mais elle fonctionne pour les bordures de ligne. Je suppose que vous pourriez faire la même chose avec les éléments composant chaque "cellule", mais je n'ai pas vérifié.

Un exemple similaire à celui de DroidNova :

<TableLayout android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
  <TableRow android:background="#FFFFFF"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_margin="1dp">
     ...
  </TableRow>
</TableLayout>

1 votes

Attention au problème de surdimensionnement délibéré, qui peut provoquer des saccades ou des bégaiements dans l'interface utilisateur si la table est grande.

0 votes

Comment puis-je définir la marge de mise en page (layout_margin) de manière programmatique sur le site Web de l'entreprise ? TableRow objet ?

0 votes

Il ajoute juste le contour autour du tableau et de ses lignes mais pas entre les colonnes.

41voto

Michael Bray Points 7397

SI si vous souhaitez simplement ajouter une ligne entre les lignes (par exemple, juste au-dessus d'une ligne "Total"), il existe une solution simple : il suffit d'ajouter un TableRow avec une couleur d'arrière-plan et une layout_height spécifique, comme ceci :

<TableRow android:layout_height="1px" android:background="#BDBDBD">
   <TextView android:layout_span="2" android:layout_height="1px" 
             android:layout_width="fill_parent" android:text="">
   </TextView>
</TableRow>

Définir android:layout_height="1px" ou l'épaisseur que vous souhaitez donner à la bordure. Remplissez autant de colonnes de TextView vides que vous le souhaitez pour qu'elles correspondent au reste de votre tableau, ou utilisez-en simplement une avec android:layout_span comme je l'ai démontré.

La sortie ressemblera à quelque chose comme ceci :

Table Border demonstrated

Si vous essayez d'ajouter des bordures plus complexes, les autres réponses déjà postées sont plus appropriées.

0 votes

Pourquoi un TextView alors que vous pouvez utiliser un View à la place ? De plus, ce n'est pas une bonne pratique de spécifier des pixels exacts. Utilisez plutôt dp/sp. Voir aussi ce fil de discussion : stackoverflow.com/questions/2025282/ .

0 votes

Merci pour les commentaires... Je suppose qu'il n'y a aucune raison d'utiliser TextView - c'était juste un exemple. Ensuite, à moins que je ne comprenne mal dp/sp (ce qui est assez probable, en fait, puisque je ne développe sur Android que depuis une semaine environ), j'utilise px parce que je ne veux qu'une ligne garantie de 1 pixel entre mes lignes, quelle que soit la résolution ou la taille de l'écran que j'utilise. J'aime les lignes très fines. D'autres utilisateurs peuvent avoir des goûts différents et utiliser d'autres unités.

0 votes

Oui mais aimez-vous les lignes très fines ! - ceci dit une bonne solution simple obtient mon vote

26voto

YasirAzzu Points 48

Ce que je voulais, c'est un tableau comme celui-ci

table image with vertical dividers

J'ai ajouté ceci dans mon styles.xml :

      <style name="Divider">
        <item name="android:layout_width">1dip</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:background">@color/divider_color</item>
    </style>

    <style name="Divider_invisible">
        <item name="android:layout_width">1dip</item>
        <item name="android:layout_height">match_parent</item>
    </style>

Puis dans mon disposition de la table :

 <TableLayout
            android:id="@+id/table"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:stretchColumns="*" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:background="#92C94A" >

                <TextView
                    android:id="@+id/textView11"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider_invisible" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView12"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/main_wo_colon"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView13"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/side_wo_colon"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView14"
                    android:paddingBottom="10dp"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:paddingTop="10dp"
                    android:text="@string/total"
                    android:textColor="@color/white"
                    android:textSize="16sp" />
            </TableRow>

            <!-- display this button in 3rd column via layout_column(zero based) -->

            <TableRow
                android:id="@+id/tableRow2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#6F9C33" >

                <TextView
                    android:id="@+id/textView21"
                    android:padding="5dp"
                    android:text="@string/servings"
                    android:textColor="@color/white"
                    android:textSize="16sp" />

                <LinearLayout
                    android:layout_width="1dp"
                    android:layout_height="match_parent" >

                    <View style="@style/Divider" />
                </LinearLayout>

..........
.......
......

25voto

Mnightmare Points 603

Vous pouvez également le faire de manière programmatique, plutôt que par le biais de xml, mais c'est un peu plus "bidouilleur". Mais donnez à un homme aucune option et vous ne lui laissez aucun choix :p.. Voici le code :

TableLayout table = new TableLayout(this);
TableRow tr = new TableRow(this);
tr.setBackgroundColor(Color.BLACK);
tr.setPadding(0, 0, 0, 2); //Border between rows

TableRow.LayoutParams llp = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 0, 2, 0);//2px right-margin

//New Cell
LinearLayout cell = new LinearLayout(this);
cell.setBackgroundColor(Color.WHITE);
cell.setLayoutParams(llp);//2px border on the right for the cell

TextView tv = new TextView(this);
tv.setText("Some Text");
tv.setPadding(0, 0, 4, 3);

cell.addView(tv);
tr.addView(cell);
//add as many cells you want to a row, using the same approach

table.addView(tr);

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X