จากตัวอย่างที่แล้วเราได้ใส่รูปลงใน ListActivity ของเราแล้วแต่ว่าทุกๆรายการเป็นรูปเดียวกันหมด วันนี้เราจะมาสร้าง ListActivity ที่แต่ละรายการสามารถใช้รูปที่แตกต่างกันได้ โดยใช้ SimpleAdapter (ชื่อ Simple แต่ไม่แน่ใจว่า Simple จริงหรือป่าว 555) ก่อนอื่นดูผลลัพธ์โปรแกรมก่อนครับ
activity_main.xml
activity_main.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
row.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center_vertical"
>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
/>
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
/>
</LinearLayout>
MainActivity.javapackage com.simplelist;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity {
final String[] fruit = {"Apple", "Banana", "Coconut", "Durian", "Guava", "Mango", "Mangosteen", "Rambutant"};
final int[] img = {R.drawable.ico_apple,
R.drawable.ico_banana,
R.drawable.ico_coconut,
R.drawable.ico_durian,
R.drawable.ico_guava,
R.drawable.ico_mango,
R.drawable.ico_mangosteen,
R.drawable.ico_rambutant
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, Object>> listArg = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = null;
int i = 0;
for(String f : fruit){
map = new HashMap<String, Object>();
map.put("name", f);
map.put("img", img[i]);
listArg.add(map);
i++;
}
SimpleAdapter adapter = new SimpleAdapter(this, listArg, R.layout.row, new String[]{"name", "img"}, new int[]{R.id.name, R.id.img});
this.setListAdapter(adapter);
}
@Override
public void onListItemClick(ListView lv, View v, int position, long id){
Toast.makeText(this, "You click " + fruit[position], Toast.LENGTH_SHORT).show();
}
}
