简体   繁体   中英

Android custom List SimpleAdapter - chose row icon

Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@android:color/black">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/icon"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView android:id="@+id/line_a"
            android:textSize="14dp"
            android:textColor="@android:color/white"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"/>

        <TextView android:id="@+id/line_b"
            android:textSize="10dp"
            android:textColor="@android:color/darker_gray"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

</LinearLayout>

Java:

    SimpleAdapter sa;
    ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
    HashMap<String,String> item;

    for(int i = 0; i < j; i++){
        item = new HashMap<String,String>();
        item.put( "line1", ListData[i][0]);
        item.put( "line2", ListData[i][1]);
        item.put( "type", ListData[i][2]);
        list.add( item );
    }

    sa = new SimpleAdapter(this, list,
            R.layout.two_lines_list,
            new String[] { "line1","line2" },
            new int[] {R.id.line_a, R.id.line_b});
                         // can you add the setImageView here? If yes, how?
    setListAdapter( sa );
}

How can I make the icon to get an image from res/drawable... depending on the type (ListData[i][2] inserted in the HashMap)? eg. if the type is "1" set icon1.png at the beginning of the 2-line-row

You should override SimpleAdapter.getView(int position, View convertView, ViewGroup parent) method, and get the list item with the current position(the first param in that method), then check the value set set the icon you want.

NOTE: you' d better use ViewHolder pattern in the getView method for performance.

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