简体   繁体   中英

How to add an icon before every ListView item text in an Android Application?

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!

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
    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>

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"

/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM