1、main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="@id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:drawSelectorOnTop="false">
</ListView>
</LinearLayout>
<!-- drawSelectorOnTop="false" :-->
<!--scrollbars="vertical" :滚动条以垂直方式显示-->
<!--ListVie声明id时必须为:"@id/android:list"-->
</LinearLayout>
2、user.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="1dip"
android:paddingBottom="1dip">
<TextView
android:id="@+id/name"
android:layout_width="180dip"
android:layout_height="30dip"
android:textSize="10pt"
android:singleLine="true"/>
<TextView
android:id="@+id/word"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="10pt"
android:gravity="right"/>
</LinearLayout>
3、Activity01.java代码:
package mars.listview2;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Activity01 extends ListActivity
{
// 实例化ArrayList链表,用来存放HashMap对象
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 实例化HashMap对象,用来存放用户名和IP
HashMap<String,String> map1 = new HashMap<String, String>();
map1.put("name", "名字1");
map1.put("word", "control——youself!");
HashMap<String,String> map2 = new HashMap<String, String>();
map2.put("name", "名字2");
map2.put("word", "control youself!");
HashMap<String,String> map3 = new HashMap<String, String>();
map3.put("name", "名字3");
map3.put("word", "control youself!");
// 添加HashMap集合到ArrayList链表中
list.add(map1);
list.add(map2);
list.add(map3);
// 实例化适配器
SimpleAdapter adapter = new SimpleAdapter(this,
list, R.layout.user,
new String[]{"name","word"}, new int[]{R.id.name,R.id.word});
setListAdapter(adapter);
}
// 当点击ListView内容时触发该事件
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
HashMap<String,String> m = list.get(position);
String str= m.get("name");
String val = m.get("word");
Toast.makeText(Activity01.this,str+" :"+val,Toast.LENGTH_SHORT).show();
}
}
4、运行效果: