package com.example.testsimpleadapter; public class MainActivity extends Activity implements OnItemClickListener{ private ListView listView; private Button btn; private List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView1); listView.setOnItemClickListener(this); initAdapter(); } private void initAdapter(){ contents = new ArrayList<Map<String, Object>>(); for (int i = 0; i < 20; i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("p_w_picpath", R.drawable.ic_launcher); map.put("text_title", "Test Title"); map.put("text_msg", "msg"); contents.add(map); } SimpleAdapter adapter = new SimpleAdapter(this, (List<Map<String, Object>>) contents, R.layout.item, new String[] { "p_w_picpath", "text_title", "text_msg"}, new int[] { R.id.p_w_picpath, R.id.text_title, R.id.text_msg}); listView.setAdapter(adapter); } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Toast.makeText(this, arg2 + "", Toast.LENGTH_SHORT).show(); } }
//item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:descendantFocusability="blocksDescendants" tools:context=".MainActivity" > <ImageView android:id="@+id/p_w_picpath" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="36dp" android:layout_marginTop="17dp" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/text_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/p_w_picpath" android:layout_toRightOf="@+id/p_w_picpath" android:text="Title Text" android:gravity="center" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/text_msg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/p_w_picpath" android:layout_alignLeft="@+id/text_title" android:layout_alignParentRight="true" android:gravity="center" android:text="msg Text" /> </RelativeLayout>
//布局文件里只有一个list