第一步:在布局文件中添加<ListView>组件
<LinearLayout 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:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.shensu.adapter.MainActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:text="姓名"
android:gravity="center"
android:textColor="#ff0000"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
<TextView
android:text="电话"
android:gravity="center"
android:textColor="#ff0000"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
<TextView
android:text="薪水"
android:gravity="center"
android:textColor="#ff0000"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
/>
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
></ListView>
</LinearLayout>
第二步:在Activity中获取listView组件
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
lv = (ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {//parent:被点击条目所在的listView view:被点击的条目
//position:当前被点击条目所绑定数据在集合中的索引值, id:当前被点击条目在listView中的id值
ListView lView = (ListView)parent;
Person person = (Person) lView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, person.getName(), 0).show();
}
});
show2();
}
第三步:为listView添加SimpleAdapter适配器
private void show() {
List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
for(int i=0;i<20;i++){
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("name", "zhangsan_"+i);
map.put("phone", "795150_"+i);
map.put("salary", "2000_"+i);
list.add(map);
}
//arg0:上下文, arg1:要填充的数据 arg2:指定要填充到哪个布局文件布局文件
//arg3:填充数据map的key值 arg4:数据填充到布局文件中的哪个View对象
SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.listview_item,
new String[]{"name","phone","salary"}, new int[]{R.id.name,R.id.phone,R.id.salary});
lv.setAdapter(simpleAdapter);
}