Comment utiliser addHeaderView pour ajouter un simple ImageView à un ListView
Mon objectif est simple. Je veux ajouter un "Rectangle Rouge" comme un headerview à un ListView
.
j'ai donc créer une activité simple
public class MainActivity extends Activity {
private String[] adapterData = new String[] { "Afghanistan", "Albania", "Algeria",
"American Samoa", "Andorra", "Angola"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv;
lv = (ListView)findViewById(R.id.list);
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.header, null, false);
lv.addHeaderView(headerView, null, false);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, adapterData));
}
}
activity_main.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0"
android:cacheColorHint="#0000"
android:paddingLeft="20dip"
android:paddingRight="20dip"
android:divider="#0000"
android:scrollbarStyle="outsideOverlay" />
list_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="0dip"
android:minHeight="40dip"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
/>
plus important, header.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dip"
android:background="#F00"/>
Mais il ne semble pas fonctionner. Rien n'est affiché.
Peut donner quelques suggestions à ce sujet? Votre aide est très appréciée.
source d'informationauteur user1764413
Vous devez vous connecter pour publier un commentaire.
Vieille question, mais je viens de copier et de l'exécuter et en effet, le rouge ne s'affiche pas.
Il vous manque une chose simple: peu importe comment vous l'appelez
inflate
vous toujours1 pour passer d'une vue parent (deuxième paramètre) afin qu'il puisse comprendre ce quiLayoutParams
sous-classe à instancier.1: il y a toujours des1 exceptions
Pour en savoir plus sur le sujet, je vous suggère fortement de: http://www.doubleencore.com/2013/05/layout-inflation-as-intended/ (la peine de lire, même quelques fois)
Votre code modifié (fichiers xml peut rester tel quel):
C'est comment j'ai ajouter un en-tête:
Vérifier cela, je dois le faire maintenant:
Suffit d'envoyer listview pour le deuxième paramètre de la gonfler méthode 🙂
Vous devez déclarer la vue d'en-tête dans un coin de fichier xml. Ensuite, le gonfler à Vue d'instance et le régler à la liste.
Vous devez appeler addHeaderView avant setAdapter à la listview.