Android ListView 添加插入数据

前面几章节,我们给 ListView 的数据都是预先定义好的,实际开发中这样的情况少之又少

要么要动态增加数据,要么要删除一些数据,要么要更改一些数据,这时候,我们的 ListView 就要同步更改才对

本节我们就来学习如何动态的更改 ListView 中的数据

基本的 demo

我们先来写一个基本的列表

又一次练写代码速度的时候到了

  1. 创建一个 空的 Android 项目 cn.twle.android.ListViewCRUD

  2. 下载 /static/i/android/golf.png 并拖到 res/drawable 目录

  3. 修改 activity_main.xml 添加一个 ListView

    <?xml version="1.0" encoding="utf-8" ?>
    <LinearLayout 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:padding="8dp" 
        android:orientation="vertical" >
    
        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
    
  4. res/layout 目录下新建一个列表项的布局 listview_item.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:padding="8dp"
        android:orientation="horizontal">
    
        <ImageView
            android:id="@+id/avatar"
            android:layout_weight="1" 
            android:layout_width="32dp"
            android:layout_height="32dp"/>
    
        <TextView
            android:id="@+id/say"
            android:layout_weight="7" 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:textSize="18sp" />
    
    </LinearLayout>
    
  5. MainActivity.java 同一目录下新建一个 BeanTalkBean.java

    package cn.twle.android.listviewcrud;
    
    public class TalkBean {
        private int avatar_id;
        private String say;
    
        public TalkBean() {}
    
        public TalkBean(int avatar_id, String say) {
            this.avatar_id = avatar_id;
            this.say = say;
        }
    
        public int getAvatarId() {
            return avatar_id;
        }
    
        public String getSay() {
            return say;
        }
    
        public void setAvatarId(int avatarId) {
            this.avatar_id = avatarId;
        }
    
        public void setSay(String say) {
            this.say = say;
        }
    }
    
  6. MainActivity.java 目录下新建一个 Adapter 文件 TalkAdapter.java

    package cn.twle.android.listviewcrud;
    
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import android.content.Context;
    
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.LayoutInflater;
    
    import java.util.LinkedList;
    
    public class TalkAdapter extends BaseAdapter {
    
        private Context mContext;
        private LinkedList<TalkBean> mData;
    
        public TalkAdapter() {}
    
        public TalkAdapter(LinkedList<TalkBean> mData, Context mContext) {
            this.mData = mData;
            this.mContext = mContext;
        }
    
        @Override
        public int getCount() {
            return mData.size();
        }
    
        @Override
        public Object getItem(int position) {
            return null;
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
    
            if(convertView == null){
    
                convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_item,parent,false);
    
                holder = new ViewHolder();
    
                holder.avatar = (ImageView) convertView.findViewById(R.id.avatar);
                holder.say = (TextView) convertView.findViewById(R.id.say);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
    
            holder.avatar.setImageResource(mData.get(position).getAvatarId());
            holder.say.setText(mData.get(position).getSay());
            return convertView;
        }
    
        private class ViewHolder{
            ImageView avatar;
            TextView  say;
        }
    
    }
    
  7. 修改 MainActivity.java

    package cn.twle.android.listviewcrud;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import android.widget.SimpleAdapter;
    import android.widget.ListView;
    import android.widget.Toast;
    import android.widget.AdapterView;
    
    import android.view.View;
    
    import java.util.LinkedList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        private ListView listview;
        private TalkAdapter talkAdapter = null;
        private List<TalkBean> mData = null;
        private int flag = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            listview = (ListView) findViewById(R.id.listview);
    
            mData = new LinkedList<TalkBean>();
            talkAdapter = new TalkAdapter((LinkedList<TalkBean>) mData,MainActivity.this);
    
            listview.setAdapter(talkAdapter);
        }
    }
    

运行后发现我们的页面并没有任何的数据,白茫茫的一片,这样的用户体验并不好

数据为空时提示用户没数据

可以调用 ListView 的一个 setEmptyView(View) 的方法,当 ListView 数据为空的时候, 显示一个对应的 View

  1. 复用上面的 demo

  2. res/layout 目录下新建一个 listview_empty.xml

    <?xml version="1.0" encoding="utf-8"?>  
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
                  android:orientation="vertical"  
                  android:layout_width="match_parent"  
                  android:layout_height="match_parent">
    
        <TextView  
            android:gravity="center"  
            android:textSize="18sp"  
            android:textColor="#333333"  
            android:text="没有可显示的数据"  
            android:layout_width="match_parent"  
            android:layout_height="match_parent"/>
    
    </LinearLayout>
    
  3. 修改 activity_main.xml 包含 listview_empty.xml

    <?xml version="1.0" encoding="utf-8" ?>
    <LinearLayout 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:padding="8dp" 
        android:orientation="vertical" >
    
        <include  
                android:id="@+id/talk_empty"  
                layout="@layout/listview_empty"/>
    
        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
    
  4. 然后修改 MainActivity.java 调用 setEmptyView(View)

    package cn.twle.android.listviewcrud;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import android.widget.ListView;
    import android.widget.Toast;
    import android.widget.AdapterView;
    
    import android.view.View;
    
    import java.util.LinkedList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        private ListView listview;
        private TalkAdapter talkAdapter = null;
        private List<TalkBean> mData = null;
        private int flag = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
    
            listview = (ListView) findViewById(R.id.listview);
    
            View listview_empty = findViewById(R.id.talk_empty);  
            listview.setEmptyView(listview_empty);
    
            mData = new LinkedList<TalkBean>();
            talkAdapter = new TalkAdapter((LinkedList<TalkBean>) mData,MainActivity.this);
    
            listview.setAdapter(talkAdapter);
        }
    }
    

运行效果如下

添加记录

我们在顶部添加一个按钮,每次点击添加一条记录


  1. 复用上面的 demo

  2. 修改 TalkAdapter.java 添加一个 add() 添加数据的方法

    public void add(TalkBean data) {
        if (mData == null) {
            mData = new LinkedList<>();
        }
        mData.add(data);
        notifyDataSetChanged();
    }
    
  3. 然后修改 activity_main.xml 添加一个按钮

    <?xml version="1.0" encoding="utf-8" ?>
    <LinearLayout 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:padding="8dp" 
        android:orientation="vertical" >
    
        <Button
            android:id="@+id/btn_add"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content" 
            android:text = "添加数据" />
    
        <include  
                android:id="@+id/talk_empty"  
                layout="@layout/listview_empty"/>
    
        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    
  4. 修改 MainActivity.java 添加按钮的点击事件

    package cn.twle.android.listviewcrud;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import android.widget.ListView;
    import android.widget.Button;
    import android.widget.Toast;
    import android.widget.AdapterView;
    
    import android.view.View;
    
    import java.util.LinkedList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        private ListView listview;
        private TalkAdapter talkAdapter = null;
        private List<TalkBean> mData = null;
        private int flag = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
    
            listview = (ListView) findViewById(R.id.listview);
    
            View listview_empty = findViewById(R.id.talk_empty);  
            listview.setEmptyView(listview_empty);
    
            mData = new LinkedList<TalkBean>();
            talkAdapter = new TalkAdapter((LinkedList<TalkBean>) mData,MainActivity.this);
    
            listview.setAdapter(talkAdapter);
    
            Button btn_add = findViewById(R.id.btn_add);
    
            btn_add.setOnClickListener(new View.OnClickListener(){
    
                @Override
                public void onClick(View v) {
                    switch (v.getId()){
                        case R.id.btn_add:
                            talkAdapter.add(new TalkBean(R.drawable.golf,"你好 " + flag));
                            flag++;
                            break;
                    }
                }
            });
        }
    }
    

TalkBean。add() 方法中的 notifyDataSetChanged() 调用很重要,它用于通知 ListView 数据已经更改,你要重新加载数据

在指定位置插入数据


如果想在特定位置插入数据,只要传递位置即可

  1. 复用上面的 demo

  2. 修改 TalkAdapter.java 添加一个方法 insert()

    // 往特定位置,添加一个元素
    public void insert(TalkBean data, int position){
        if (mData == null) {
            mData = new LinkedList<>();
        }
    
        int len = mData.size();
    
        if ( 0 > position )
        {
            position = 0;
        }
    
        if ( position > len )
        {
            position = len;
        }
    
        mData.add(position,data);
        notifyDataSetChanged();
    }
    
  3. 然后修改布局添加一个 插入数据按钮

    <?xml version="1.0" encoding="utf-8" ?>
    <LinearLayout 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:padding="8dp" 
        android:orientation="vertical" >
    
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp" 
            android:orientation="horizontal" >
    
            <Button
                android:id="@+id/btn_add"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content" 
                android:text = "添加" />
    
            <Button
                android:id="@+id/btn_insert"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content" 
                android:text = "插入数据到位置 3 " />
    
        </LinearLayout>
    
        <include  
                android:id="@+id/talk_empty"  
                layout="@layout/listview_empty"/>
    
        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    
  4. 修改 MainActivity.java 添加按钮的点击事件

    package cn.twle.android.listviewcrud;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    import android.widget.ListView;
    import android.widget.Button;
    import android.widget.Toast;
    import android.widget.AdapterView;
    
    import android.view.View;
    
    import java.util.LinkedList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        private ListView listview;
        private TalkAdapter talkAdapter = null;
        private List<TalkBean> mData = null;
        private int flag = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
    
            listview = (ListView) findViewById(R.id.listview);
    
            View listview_empty = findViewById(R.id.talk_empty);  
            listview.setEmptyView(listview_empty);
    
            mData = new LinkedList<TalkBean>();
            talkAdapter = new TalkAdapter((LinkedList<TalkBean>) mData,MainActivity.this);
    
            listview.setAdapter(talkAdapter);
    
            Button btn_add = findViewById(R.id.btn_add);
            Button btn_insert = findViewById(R.id.btn_insert);
    
            btn_add.setOnClickListener(this);
            btn_insert.setOnClickListener(this);
        }
    
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn_add:
                    talkAdapter.add(new TalkBean(R.drawable.golf,"你好 " + flag));
                    flag++;
                    break;
    
                case R.id.btn_insert:
                    // position  0 开始算的
                    talkAdapter.insert(new TalkBean(R.drawable.golf,"你好 " + flag),2);
                    flag++;
                    break;
            }
        }
    }
    

Android 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.