ListView组件和SimpleAdapter
一、要求
使用ListView组件和SimpleAdapte实现简单的UI的简单页面
二、具体的代码实现
1、activity_main.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: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=".MainActivity" >
<ListView
android:id="@+id/Lv02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
>
</ListView>
</RelativeLayout>
2、MainActivity.java
package com.example.listview2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.listview2.MainActivity;
import com.example.listview2.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private List<Map<String, ?>> date;
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.Lv02);
date = getData();
// 创建SimpleAdapter适配器,装载数据
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, date,
android.R.layout.simple_list_item_2, new String[] { "name",
"address" }, new int[] { android.R.id.text1,
android.R.id.text2 });
// 控件与适配器进行绑定
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterview, View view, int position,
long id) {
Toast.makeText(getApplicationContext(), "姓名是:"+date.get(position).get("name")+"、"+"地址是:"+date.get(position).get("address"),Toast.LENGTH_SHORT).show();
}
});
}
private List<Map<String, ?>> getData() {
List<Map<String, ?>> newdata = new ArrayList<Map<String, ?>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", "小龙女");
map1.put("address", "终南山古墓");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", "公孙止");
map2.put("address", "绝情谷");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("name", "黄药师");
map3.put("address", "桃花岛");
newdata.add(map1);
newdata.add(map2);
newdata.add(map3);
return newdata;
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
三、运行效果图