该程序完成如下功能:
1 在ListView中显示多个学生的名字。
2 点击ListView中的条目,查询并显示该学生的年龄、性别、照片等信息。
效果图:
![]()
student.java
- package com.lingdududu.listview;
-
- public class Student {
-
- public String sname;
- public String ssex;
- public int sage;
-
- Student(String name,String sex,int age){
- sname=name;
- ssex=sex;
- sage=age;
- }
-
- void Stuedent(String name){
- sname=name;
- }
-
- public String getName(){
- return sname;
- }
-
- public String getSex(){
- return ssex;
- }
-
- public int getAge(){
- return sage;
- }
- public String toString (){
- return sname;
- }
-
-
- public String getStuIfo(){
- return ("姓名:"+sname+"\n性别:"+ssex+"\n年龄:"+sage);
- }
- }
ListViewActivity.java
- package com.lingdududu.listview;
-
- import java.util.ArrayList;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemClickListener;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
-
-
-
-
-
- public class ListViewActivity extends Activity {
- private ListView lv;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
-
- final int[] stu_pic = {
- R.drawable.pic1,
- R.drawable.pic2,
- R.drawable.pic3,
- R.drawable.pic4,
- R.drawable.pic5,
- R.drawable.pic6};
-
- final AlertDialog.Builder builder = new AlertDialog.Builder(this);
-
- lv=(ListView)findViewById(R.id.list);
-
-
- final ArrayList<Student>students = new ArrayList<Student>();
-
- students.add(new Student("小张","女",21));
- students.add(new Student("小明","男",22));
- students.add(new Student("小王","男",23));
- students.add(new Student("小丽","女",21));
- students.add(new Student("小红","女",22));
- students.add(new Student("小周","男",23));
-
-
- ArrayAdapter<Student> adapter = new ArrayAdapter<Student>
- (this,
- android.R.layout.simple_list_item_1,
- students);
-
- lv.setAdapter(adapter);
- lv.setOnItemClickListener(new OnItemClickListener() {
-
-
-
-
-
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
- long arg3){
-
- builder.setMessage(students.get(arg2).getStuIfo())
-
- .setIcon(stu_pic[arg2])
- .setTitle("你好,这是我的详细信息!")
- .setPositiveButton("确定", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
-
- }
- });
-
- AlertDialog ad = builder.create();
-
- ad.show();
- }
- });
- }
- }
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ListView
- android:id="@+id/list"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
附件:http://down.51cto.com/data/2359281
本文转自 lingdududu 51CTO博客,原文链接:
http://blog.51cto.com/liangruijun/716529