androidimageiconslistpreference

How to set icon in ListPreference's item in android


I want to set the icon in ListPreference items in android.

What to write in ListPreference or where to write to set the list items icon?


Solution

  • You need to use a custom layout for your ListPreference.

    eg:

    <android.preference.ListPreference
                    android:layout="@layout/your_custom_layout"
                     ....
    />
    

    And add what you want to your custom layout.

    eg:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:paddingRight="?android:attr/scrollbarSize">
    
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_margin="@dimen/preferences_layout_margin">
    
            <ImageView android:id="@+id/yourIconId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true" /> <!-- here i've added an ImageView for icon -->
    
            <TextView android:id="@android:id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:ellipsize="marquee"
                android:fadingEdge="horizontal"
                android:layout_toRightOf="@+id/iconImageView"
                android:layout_marginLeft="@dimen/preferences_icon_margin" />
    
            <TextView android:id="@android:id/summary"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@android:id/title"
                android:layout_alignLeft="@android:id/title"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:maxLines="2" />
    
        </RelativeLayout>
        <!-- Preference should place its actual preference widget here. -->
        <LinearLayout android:id="@android:id/widget_frame"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:gravity="center_vertical"
            android:orientation="vertical" />
    
    </LinearLayout>