user3194026
user3194026

Reputation: 9

Add Header to an ListView in Android

I want to add an image as header to a ListView. It happens to work - BUT there is much space around the image, although i have tried changing the paddings... it does not work.

this is my main activity

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity" >

<ListView 
android:id="@+id/LV_Home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></ListView>
</RelativeLayout>

this is my header

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

<ImageView 
android:src="@drawable/homeimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:paddingBottom="0dp" />

</LinearLayout>

and this is how i added the header:

String[] array = getResources().getStringArray(R.array.entries);

ListView lv = (ListView) findViewById(R.id.LV_Home);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,   android.R.layout.simple_list_item_1, array);
View header = getLayoutInflater().inflate(R.layout.header_main_menue, null);
lv.addHeaderView(header);
lv.setAdapter(aa);

Upvotes: 0

Views: 396

Answers (1)

Phant&#244;maxx
Phant&#244;maxx

Reputation: 38098

You can do so:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity"
    >
    <ImageView 
        android:id="@+id/header"
        android:src="@drawable/homeimage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="0dp"
        android:paddingBottom="0dp"
    />
    <ListView 
        android:id="@+id/LV_Home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/header"
    />
</RelativeLayout>

And comment out these lines:

/*
View header = getLayoutInflater().inflate(R.layout.header_main_menue, null);
lv.addHeaderView(header);
lv.setAdapter(aa);
*/

Note that now you have only one xml instead of two (the header is now included in the ListView's layout)

Upvotes: 1

Related Questions