Android对ListView控件增删改查

来源:互联网 发布:趋势密码软件好吗 编辑:程序博客网 时间:2024/06/06 08:43

在Android开发中ListView控件经常用到,下面这个示例可以手动输入数据,在ListView控件上增加一个Item,同时在每一个Item上有一个删除按钮可以删除该条目,界面如下。

(1)工程目录结构

ListViewAdapter.Java 是ListView的适配类

StudentBean.java 是ListView Item的数据

MainActivity.java是启动类

CommonConstant.java 是常量

activity_main.xml是主的布局文件

add_user.xml是界面上添加学生姓名、描述信息和Save按钮的布局文件

title_tool.xml是自定义的标题布局文件

student_listview.xml是ListView每一个Item的布局文件


(2)布局文件

这几个布局文件都采用LinearLayout布局,代码如下
active_main.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:orientation="vertical"  
  8.     tools:context="com.nii.orcale.MainActivity">  
  9.   
  10.     <include layout="@layout/title_toolbar"></include>  
  11.   
  12.     <include layout="@layout/add_user"></include>  
  13.   
  14.     <ListView  
  15.             android:id="@+id/listView"  
  16.             android:layout_width="match_parent"  
  17.             android:layout_height="wrap_content" >  
  18.     </ListView>  
  19. </LinearLayout>  
title_toolbar.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.                 android:id="@+id/layout_titlebar"  
  4.                 android:layout_width="match_parent"  
  5.                 android:layout_height="52dp"  
  6.   
  7.                 android:background="#ed4255">  
  8.   
  9.     <TextView  
  10.             android:id="@+id/text_title"  
  11.             android:layout_width="match_parent"  
  12.             android:layout_height="match_parent"  
  13.             android:ellipsize="marquee"  
  14.             android:gravity="center_horizontal|center"  
  15.             android:singleLine="true"  
  16.             android:text="@string/title"  
  17.             android:textColor="#ffffffff"  
  18.             android:textSize="20dp"/>  
  19.   
  20. </RelativeLayout>  
add_user.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:orientation="vertical"  
  8.     tools:context="com.nii.orcale.MainActivity">  
  9.   
  10.     <include layout="@layout/title_toolbar"></include>  
  11.   
  12.     <include layout="@layout/add_user"></include>  
  13.   
  14.     <ListView  
  15.             android:id="@+id/listView"  
  16.             android:layout_width="match_parent"  
  17.             android:layout_height="wrap_content" >  
  18.     </ListView>  
  19. </LinearLayout>  
student_listview.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:orientation="horizontal"  
  4.               android:layout_width="match_parent"  
  5.               android:layout_height="match_parent"  
  6.               android:paddingBottom="5dp"  
  7.               android:paddingTop="5dp">  
  8.   
  9.     <ImageView  
  10.             android:layout_width="50dp"  
  11.             android:layout_height="50dp"  
  12.             android:id="@+id/stuIcon"  
  13.             android:layout_gravity="center"  
  14.             android:src="@mipmap/stu1"  
  15.     />  
  16.       
  17.     <LinearLayout  
  18.             android:layout_gravity="center"  
  19.             android:orientation="vertical"  
  20.             android:paddingLeft="15dp"  
  21.             android:layout_weight="1"  
  22.             android:layout_width="match_parent"  
  23.             android:layout_height="wrap_content">  
  24.   
  25.   
  26.         <TextView  
  27.                 android:singleLine="true"  
  28.                 android:id="@+id/showStuName"  
  29.                 android:text="showStuName"  
  30.                 android:textColor="#000000"  
  31.                 android:textSize="16sp"  
  32.                 android:layout_marginBottom="3dp"  
  33.                 android:layout_width="fill_parent"  
  34.                 android:layout_height="wrap_content"/>  
  35.   
  36.         <TextView  
  37.                 android:singleLine="true"  
  38.                 android:id="@+id/showStuDesc"  
  39.                 android:text="stuDesc"  
  40.                 android:textColor="#000000"  
  41.                 android:textSize="16sp"  
  42.                 android:layout_marginBottom="3dp"  
  43.                 android:layout_width="fill_parent"  
  44.                 android:layout_height="wrap_content"/>  
  45.     </LinearLayout>  
  46.   
  47.     <LinearLayout  
  48.             android:orientation="horizontal"  
  49.             android:layout_gravity="center"  
  50.             android:layout_width="wrap_content"  
  51.             android:layout_weight="0"  
  52.             android:layout_height="wrap_content">  
  53.   
  54.         <Button  
  55.                 android:layout_gravity="center"  
  56.                 android:text="Delete"  
  57.                 android:id="@+id/showDeleteButton"  
  58.                 android:layout_width="wrap_content"  
  59.                 android:layout_height="wrap_content"/>  
  60.     </LinearLayout>  
  61.   
  62.   
  63.   
  64. </LinearLayout>  
AndroidManifest.xml文件
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.nii.orcale" >  
  4.   
  5.     <application  
  6.         android:allowBackup="true"  
  7.         android:icon="@mipmap/ic_launcher"  
  8.         android:label="@string/app_name"  
  9.         android:supportsRtl="true"  
  10.         android:theme="@style/Theme.AppCompat.Light.NoActionBar" >  
  11.         <activity android:name=".MainActivity" >  
  12.             <intent-filter>  
  13.                 <action android:name="android.intent.action.MAIN" />  
  14.   
  15.                 <category android:name="android.intent.category.LAUNCHER" />  
  16.             </intent-filter>  
  17.         </activity>  
  18.     </application>  
  19.   
  20. </manifest>  

3、代码逻辑实现.

ListView的适配器采用BaseAdapter,界面上的数据放入List中。
private List<StudentBean> studentBeanList = new ArrayList<StudentBean>();
notifyDataSetChanged
当点击Save按钮的时候,把界面上输入的姓名和描述信息放入添加到studentBeanList 中,同时出发Adapter的notifyDataSetChanged事件,重新加载界面数据。
在点击每一个Item的Delete按钮时候,把studentBeanList 中数据移除,同时也发出Adapter的notifyDataSetChanged事件,重新加载界面数据。

代码如下:
MainActivity.java
[java] view plain copy
  1. package com.nii.orcale;  
  2.   
  3. import android.content.Context;  
  4. import android.os.Bundle;  
  5. import android.support.v7.app.AppCompatActivity;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8. import android.widget.EditText;  
  9. import android.widget.ListView;  
  10. import android.widget.Toast;  
  11. import com.nii.orcale.adapter.ListViewAdapter;  
  12. import com.nii.orcale.bean.StudentBean;  
  13. import org.apache.commons.lang3.StringUtils;  
  14. import java.util.ArrayList;  
  15. import java.util.List;  
  16.   
  17. public class MainActivity extends AppCompatActivity  
  18. {  
  19.   
  20.     /** 
  21.      * Context 
  22.      */  
  23.     private Context mContext;  
  24.   
  25.   
  26.     /** 
  27.      * listview 
  28.      */  
  29.     private ListView listView;  
  30.   
  31.     /** 
  32.      * 适配器 
  33.      */  
  34.     private ListViewAdapter listViewAdapter;  
  35.   
  36.     /** 
  37.      * 保存数据 
  38.      */  
  39.     private List<StudentBean> studentBeanList = new ArrayList<StudentBean>();  
  40.   
  41.     @Override  
  42.     protected void onCreate(Bundle savedInstanceState)  
  43.     {  
  44.         super.onCreate(savedInstanceState);  
  45.         setContentView(R.layout.activity_main);  
  46.   
  47.         this.mContext = this;  
  48.   
  49.         //加载listview  
  50.         listView = (ListView) findViewById(R.id.listView);  
  51.         listViewAdapter = new ListViewAdapter(mContext,studentBeanList);  
  52.         listView.setAdapter(listViewAdapter);  
  53.   
  54.         //save button的点击事件  
  55.         Button saveButton = (Button) findViewById(R.id.saveButton);  
  56.         saveButton.setOnClickListener(new View.OnClickListener()  
  57.         {  
  58.             @Override  
  59.             public void onClick(View v)  
  60.             {  
  61.                 saveStudentMessage();  
  62.             }  
  63.         });  
  64.     }  
  65.   
  66.   
  67.   
  68.     /** 
  69.      * 保存学生的信息 
  70.      */  
  71.     private void saveStudentMessage()  
  72.     {  
  73.         EditText nameEditText = (EditText) findViewById(R.id.nameEditText);  
  74.         EditText descEditText = (EditText) findViewById(R.id.descEditText);  
  75.   
  76.         if (StringUtils.isEmpty(nameEditText.getText().toString())  
  77.                 || StringUtils.isEmpty(descEditText.getText().toString()))  
  78.         {  
  79.             Toast.makeText(mContext,"姓名和描述信息都不能为空",Toast.LENGTH_SHORT).show();  
  80.             return;  
  81.         }  
  82.   
  83.         //判断该学生是否存在  
  84.         for (StudentBean studentBean : studentBeanList)  
  85.         {  
  86.             if (StringUtils.equals(studentBean.getName(),nameEditText.getText().toString()))  
  87.             {  
  88.                 Toast.makeText(mContext,nameEditText.getText().toString() + "已经存在",Toast.LENGTH_SHORT).show();  
  89.                 return;  
  90.             }  
  91.         }  
  92.   
  93.   
  94.         StudentBean studentBean = new StudentBean(nameEditText.getText().toString(),descEditText.getText().toString());  
  95.         studentBeanList.add(studentBean);  
  96.   
  97.         listViewAdapter.notifyDataSetChanged();  
  98.     }  
  99.   
  100. }  

适配器ListViewAdapter.java
[java] view plain copy
  1. package com.nii.orcale.adapter;  
  2.   
  3. import android.content.Context;  
  4. import android.view.LayoutInflater;  
  5. import android.view.View;  
  6. import android.view.ViewGroup;  
  7. import android.widget.BaseAdapter;  
  8. import android.widget.Button;  
  9. import android.widget.TextView;  
  10. import com.nii.orcale.R;  
  11. import com.nii.orcale.bean.StudentBean;  
  12.   
  13. import java.util.ArrayList;  
  14. import java.util.List;  
  15. import java.util.Map;  
  16.   
  17. /** 
  18.  * Created by wzj on 2017/2/11. 
  19.  */  
  20. public class ListViewAdapter extends BaseAdapter  
  21. {  
  22.     /** 
  23.      * Context 
  24.      */  
  25.     private Context mContext;  
  26.   
  27.     /** 
  28.      * 数据 
  29.      */  
  30.     private List<StudentBean> studentBeanList;  
  31.   
  32.     /** 
  33.      * 构造函数 
  34.      * @param context context 
  35.      * @param studentBeanList studentBeanMap 
  36.      */  
  37.     public ListViewAdapter(Context context,List<StudentBean> studentBeanList)  
  38.     {  
  39.         this.mContext = context;  
  40.         this.studentBeanList = studentBeanList;  
  41.     }  
  42.   
  43.     /** 
  44.      * How many items are in the data set represented by this Adapter. 
  45.      * 
  46.      * @return Count of items. 
  47.      */  
  48.     @Override  
  49.     public int getCount()  
  50.     {  
  51.         return studentBeanList.size();  
  52.     }  
  53.   
  54.     /** 
  55.      * Get the data item associated with the specified position in the data set. 
  56.      * 
  57.      * @param position Position of the item whose data we want within the adapter's 
  58.      *                 data set. 
  59.      * @return The data at the specified position. 
  60.      */  
  61.     @Override  
  62.     public Object getItem(int position)  
  63.     {  
  64.         return null;  
  65.     }  
  66.   
  67.     /** 
  68.      * Get the row id associated with the specified position in the list. 
  69.      * 
  70.      * @param position The position of the item within the adapter's data set whose row id we want. 
  71.      * @return The id of the item at the specified position. 
  72.      */  
  73.     @Override  
  74.     public long getItemId(int position)  
  75.     {  
  76.         return 0;  
  77.     }  
  78.   
  79.     /** 
  80.      * Get a View that displays the data at the specified position in the data set. You can either 
  81.      * create a View manually or inflate it from an XML layout file. When the View is inflated, the 
  82.      * parent View (GridView, ListView...) will apply default layout parameters unless you use 
  83.      * {@link LayoutInflater#inflate(int, ViewGroup, boolean)} 
  84.      * to specify a root view and to prevent attachment to the root. 
  85.      * 
  86.      * @param position    The position of the item within the adapter's data set of the item whose view 
  87.      *                    we want. 
  88.      * @param convertView The old view to reuse, if possible. Note: You should check that this view 
  89.      *                    is non-null and of an appropriate type before using. If it is not possible to convert 
  90.      *                    this view to display the correct data, this method can create a new view. 
  91.      *                    Heterogeneous lists can specify their number of view types, so that this View is 
  92.      *                    always of the right type (see {@link #getViewTypeCount()} and 
  93.      *                    {@link #getItemViewType(int)}). 
  94.      * @param parent      The parent that this view will eventually be attached to 
  95.      * @return A View corresponding to the data at the specified position. 
  96.      */  
  97.     @Override  
  98.     public View getView(int position, View convertView, ViewGroup parent)  
  99.     {  
  100.         View view = null;  
  101.         if (convertView != null)  
  102.         {  
  103.             view = convertView;  
  104.         }  
  105.         else  
  106.         {  
  107.             view = View.inflate(mContext, R.layout.student_listview, null);  
  108.         }  
  109.   
  110.         StudentBean studentBean = studentBeanList.get(position);  
  111.         if (studentBean == null)  
  112.         {  
  113.             studentBean = new StudentBean("NoName","NoDesc");  
  114.         }  
  115.   
  116.         //更新数据  
  117.         final TextView nameTextView = (TextView) view.findViewById(R.id.showStuName);  
  118.         nameTextView.setText(studentBean.getName());  
  119.   
  120.         TextView descTextView = (TextView)view.findViewById(R.id.showStuDesc);  
  121.         descTextView.setText(studentBean.getDesc());  
  122.   
  123.         final int removePosition = position;  
  124.   
  125.         //删除按钮点击事件  
  126.         Button deleteButton = (Button)view.findViewById(R.id.showDeleteButton);  
  127.         deleteButton.setOnClickListener(new View.OnClickListener()  
  128.         {  
  129.             @Override  
  130.             public void onClick(View v)  
  131.             {  
  132.                 deleteButtonAction(removePosition);  
  133.             }  
  134.         });  
  135.   
  136.   
  137.         return view;  
  138.     }  
  139.   
  140.     private void deleteButtonAction(int position)  
  141.     {  
  142.         studentBeanList.remove(position);  
  143.   
  144.         notifyDataSetChanged();  
  145.     }  
  146. }  

数据对象StuentBean.java
[java] view plain copy
  1. package com.nii.orcale.bean;  
  2.   
  3. /** 
  4.  * Created by wzj on 2017/2/12. 
  5.  */  
  6. public class StudentBean  
  7. {  
  8.     private int id;  
  9.   
  10.     private String name;  
  11.   
  12.     private int score;  
  13.   
  14.     private String desc;  
  15.   
  16.     public StudentBean()  
  17.     {  
  18.   
  19.     }  
  20.   
  21.     public StudentBean(String name, String desc)  
  22.     {  
  23.         this.name = name;  
  24.         this.desc = desc;  
  25.     }  
  26.   
  27.     public int getId()  
  28.     {  
  29.         return id;  
  30.     }  
  31.   
  32.     public void setId(int id)  
  33.     {  
  34.         this.id = id;  
  35.     }  
  36.   
  37.     public String getName()  
  38.     {  
  39.         return name;  
  40.     }  
  41.   
  42.     public void setName(String name)  
  43.     {  
  44.         this.name = name;  
  45.     }  
  46.   
  47.     public int getScore()  
  48.     {  
  49.         return score;  
  50.     }  
  51.   
  52.     public void setScore(int score)  
  53.     {  
  54.         this.score = score;  
  55.     }  
  56.   
  57.     public String getDesc()  
  58.     {  
  59.         return desc;  
  60.     }  
  61.   
  62.     public void setDesc(String desc)  
  63.     {  
  64.         this.desc = desc;  
  65.     }  
  66. }  

注意:
1、需要在给ListView每一个Item上都要添加事件。

代码github链接:https://github.com/HelloKittyNII/ModuleCode/tree/master/android/03.listview
0 0
原创粉丝点击