tags:

views:

49

answers:

2

How can I add an icon before every ListView item text in an Android application?

Here is the current list_item xml that is called to populate the list:

<?xml version="1.0" encoding="utf-8"?>


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:gravity="center_vertical"
    android:padding="5dip"
    android:background="@color/darkblue"
/>   

I attempted to add a ImageView before it, but it didn't show at all. Then I added a RelativeLayout around the entire thing and tried positioning them, but still it didn't show.

Any ideas?

Thanks!

+2  A: 

You can use a Relative Layout, just add the property android:layout_toRightOf to your TextView::

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" 
 android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal">
<ImageView
        android:id="@+id/myIcon"
        android:layout_width="25px"
        android:layout_height="25px"       
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_centerVertical="true"
        android:focusable="false"
        android:padding="4px"
        />  
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:gravity="center_vertical"
    android:padding="5dip"
    android:background="@color/darkblue"
android:layout_toRightOf="@id/myIcon"  
/>   

</RelativeLayout>
Jorgesys
+1  A: 

Better way to do this is to use drawableLeft, drawableRight, drawableTop, drawableBottom tags:

<?xml version="1.0" encoding="utf-8"?>


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:gravity="center_vertical"
    android:padding="5dip"
    android:background="@color/darkblue"
    android:drawableLeft="@drawable/yourPicture"

/> 
Auriukas