android中listview的使用实例
user.xml
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!--用户名文本-->
<TextViewandroid:id="@+id/userNameId"android:layout_width="wrap_content"
android:layout_height="wrap_content"android:textSize="10pt"
android:gravity="left"/>
<!--IP文本-->
<TextViewandroid:id="@+id/ipId"android:layout_width="fill_parent"
android:layout_height="wrap_content"android:textSize="10pt"
android:gravity="right"/>
</LinearLayout>
main.xml
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayoutandroid:layout_width="fill_parent"
android:layout_height="wrap_content"android:orientation="vertical"
android:paddingLeft="10px"android:paddingRight="10px"
android:paddingTop="10px"android:paddingBottom="10px">
<ListViewandroid:id="@id/android:list"android:layout_width="fill_parent"
android:layout_height="wrap_content"android:scrollbars="vertical"
android:drawSelectorOnTop="true"/>
</LinearLayout>
</LinearLayout>
ListViewActivity.java
packagecom.duoguo.android;
importjava.util.ArrayList;
importjava.util.HashMap;
importandroid.app.ListActivity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.ListView;
importandroid.widget.SimpleAdapter;
/**
*ListView的使用
*
*@authorshyboy([email protected])
*
*/
publicclassListViewActivityextendsListActivity{
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String,String>>list=newArrayList<HashMap<String,String>>();//实例化ArrayList链表,用来存放HashMap对象
//实例化HashMap对象,用来存放用户名和IP
HashMap<String,String>map1=newHashMap<String,String>();
map1.put("user_name","shyboy");
map1.put("user_ip","192.168.0.1");
HashMap<String,String>map2=newHashMap<String,String>();
map2.put("user_name","playboy");
map2.put("user_ip","192.168.0.2");
HashMap<String,String>map3=newHashMap<String,String>();
map3.put("user_name","simplyboy");
map3.put("user_ip","192.168.0.3");
//添加HashMap集合到ArrayList链表中
list.add(map1);
list.add(map2);
list.add(map3);
SimpleAdapterlistSimpleAdapter=newSimpleAdapter(this,list,
R.layout.user,newString[]{"user_name","user_ip"},
newint[]{R.id.userNameId,R.id.ipId});//实例化适配器
this.setListAdapter(listSimpleAdapter);
}
//当点击ListView内容时触发该事件
@Override
protectedvoidonListItemClick(ListViewl,Viewv,intposition,longid){
super.onListItemClick(l,v,position,id);
System.out.println("idis:"+id);
System.out.println("positionis:"+position);
}
}