源文件
public class MainActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); final Context context = this; //数据 final String[] names = new String[]{"张三","李四","王五"}; String[] desc = new String[]{"张三好","李四坏","王五中庸"}; int[] imageId = new int[]{R.mipmap.screen_low,R.mipmap.screen_low,R.mipmap.screen_low}; //列表项摆放顺序 = ArrayList数据的顺序 List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>(); for(int i = 0 ; i<names.length;i++){ Map<String,Object> listItem = new HashMap<String,Object>(); listItem.put("header",imageId[i]); listItem.put("name",names[i]); listItem.put("desc",desc[i]); listItems.add(listItem); } SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems, R.layout.comp_simpleadapter, //列表项中数据和布局对应关系 new String[]{"header","name","desc"}, new int[]{R.id.header,R.id.name,R.id.desc}); setListAdapter(simpleAdapter); /////////////////////////////////////////////////////////////////// //点击事件:列表项添加单击监听器 this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String name = names[position]; Toast.makeText(context,name+"被点击了",Toast.LENGTH_SHORT).show(); } }); }}
列表项视图文件
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/header" /> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/name"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/desc"/> </LinearLayout></LinearLayout>
时间: 2024-10-15 07:52:46