Android ListView的數(shù)據(jù)更新問題

2023-03-31 13:42 更新

本節(jié)引言:

我們前面已經(jīng)學(xué)習(xí)了ListView的一些基本用法咧,但是細(xì)心的你可能發(fā)現(xiàn)了,我們的數(shù)據(jù) 一開始定義好的,都是靜態(tài)的,但是實際開發(fā)中,我們的數(shù)據(jù)往往都是動態(tài)變化的,比如 我增刪該了某一列,那么列表顯示的數(shù)據(jù)也應(yīng)該進(jìn)行同步的更新,那么本節(jié)我們就來探討 下ListView數(shù)據(jù)更新的問題,包括全部更新,以及更新其中的一項,那么開始本節(jié)內(nèi)容!~ 


1.先寫個正常的demo先

好的,先寫個正常的Demo先,等下我們再慢慢調(diào):

entity類:Data.java

/**
 * Created by Jay on 2015/9/21 0021.
 */
public class Data {
    private int imgId;
    private String content;

    public Data() {}

    public Data(int imgId, String content) {
        this.imgId = imgId;
        this.content = content;
    }

    public int getImgId() {
        return imgId;
    }

    public String getContent() {
        return content;
    }

    public void setImgId(int imgId) {
        this.imgId = imgId;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

Activity布局以及列表項布局

activity_main.xml

<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:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/list_one"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

item_list.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="horizontal">

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="56dp"
        android:layout_height="56dp"/>

    <TextView
        android:id="@+id/txt_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="10dp"
        android:textSize="18sp" />

</LinearLayout>

自定義BaseAdapter的實現(xiàn):MyAdapter.java

/**
 * Created by Jay on 2015/9/21 0021.
 */
public class MyAdapter extends BaseAdapter {

    private Context mContext;
    private LinkedList<Data> mData;

    public MyAdapter() {}

    public MyAdapter(LinkedList<Data> 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.item_list,parent,false);
            holder = new ViewHolder();
            holder.img_icon = (ImageView) convertView.findViewById(R.id.img_icon);
            holder.txt_content = (TextView) convertView.findViewById(R.id.txt_content);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        holder.img_icon.setImageResource(mData.get(position).getImgId());
        holder.txt_content.setText(mData.get(position).getContent());
        return convertView;
    }

    private class ViewHolder{
        ImageView img_icon;
        TextView txt_content;
    }

}

MainActivity.java的編寫:

public class MainActivity extends AppCompatActivity {

    private ListView list_one;
    private MyAdapter mAdapter = null;
    private List<Data> mData = null;
    private Context mContext = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        bindViews();
        mData = new LinkedList<Data>();
        mAdapter = new MyAdapter((LinkedList<Data>) mData,mContext);
        list_one.setAdapter(mAdapter);
    }

    private void bindViews(){
        list_one = (ListView) findViewById(R.id.list_one);
    }

}

可以運行,運行后發(fā)現(xiàn)我們的頁面并沒有任何的數(shù)據(jù),白茫茫的一片,這樣的用戶體驗并不好, 我們可以通過調(diào)用ListView的一個setEmptyView(View)的方法,當(dāng)ListView數(shù)據(jù)為空的時候, 顯示一個對應(yīng)的View,另外發(fā)現(xiàn)這個方法很奇葩,動態(tài)添加的View,竟然無效,只能在ListView 所在的布局文件中添加當(dāng)ListView無數(shù)據(jù)時,想顯示的View,另外用這個setEmptyView設(shè)置后的 View,加載的時候竟然不會顯示出來,好靈異....比如這里的是沒有數(shù)據(jù)時顯示一個沒有數(shù)據(jù) 的TextView,部分代碼如下:

<TextView
        android:id="@+id/txt_empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="15pt"
        android:textColor="#000000"/>

txt_empty = (TextView) findViewById(R.id.txt_empty);    
txt_empty.setText("暫無數(shù)據(jù)~");
list_one.setEmptyView(txt_empty);

當(dāng)然除了這種方法外我們還可以定義一個與ListView一樣大小位置的布局,然后設(shè)置, android:visibility="gone",在Java代碼中對mData集合的size進(jìn)行判斷,如果==0, 說明沒數(shù)據(jù),讓這個布局顯示出來,當(dāng)有數(shù)據(jù)的時候讓這個布局隱藏~


2.添加一條記錄

好的,我們弄個添加按鈕,沒按一次添加一條記錄哈~

運行效果圖:

代碼實現(xiàn)

在我們自定義的BaseAdapter中定義一個方法,方法內(nèi)容如下:

public void add(Data data) {
    if (mData == null) {
        mData = new LinkedList<>();
    }
    mData.add(data);
    notifyDataSetChanged();
}

然后布局自己加個按鈕,然后設(shè)置下事件,代碼如下:

private Button btn_add;
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(this);

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btn_add:
            mAdapter.add(new Data(R.mipmap.ic_icon_qitao,"給豬哥跪了~~~ x " + flag));
            flag++;
            break;
    }
}

嘿嘿,成了,添加數(shù)據(jù)就這么簡單~,如果你想插入到特定位置,也行,我們Adapter類里,再另外 寫一個方法:

//往特定位置,添加一個元素
public void add(int position,Data data){
    if (mData == null) {
        mData = new LinkedList<>();
    }
    mData.add(position,data);
    notifyDataSetChanged();
}

然后加個按鈕,寫個事件:

private Button btn_add2;
btn_add2 = (Button) findViewById(R.id.btn_add2);
btn_add2.setOnClickListener(this);

case R.id.btn_add2:
//position從0開始算的
mAdapter.add(4,new Data(R.mipmap.ic_icon_qitao,"給豬哥跪了~~~ x " + flag));
break;

運行效果圖:

可以看到我們的第九項插入到了第五個位置~


3.刪除某一項

同樣的,我們寫兩個方法,一個直接刪對象,一個根據(jù)游標(biāo)來刪:

public void remove(Data data) {
    if(mData != null) {
        mData.remove(data);
    }
    notifyDataSetChanged();
}

public void remove(int position) {
    if(mData != null) {
        mData.remove(position);
    }
    notifyDataSetChanged();
}

然后加兩個Button,調(diào)用下這兩個方法:

case R.id.btn_remove:
    mAdapter.remove(mData_5);
    break;
case R.id.btn_remove2:
    mAdapter.remove(2);
    break;

運行效果圖

從圖中我們可以看到,第五項被移除了,然后點擊游標(biāo)刪除數(shù)據(jù),一直刪的是第三項!


4.移除所有的記錄:

這個更加簡單,直接調(diào)用clear方法即可!方法代碼如下:

public void clear() {
    if(mData != null) {
        mData.clear();
    }
    notifyDataSetChanged();
}

5.更新某一個記錄

細(xì)心的你應(yīng)該發(fā)現(xiàn)了,進(jìn)行了數(shù)據(jù)修改操作后,都會調(diào)用一個notifyDataSetChanged(); 一開始我以為:

notifyDataSetChanged()會把界面上現(xiàn)實的的item都重繪一次,這樣會影響ui性能吧,如果數(shù)據(jù)量 很大,但是我改變一項就要重新繪制所有的item,這肯定不合理是吧!于是乎,我用了一個傻辦法 來修改某個Item中控件的值,我在Java代碼中寫了這樣一段代碼:

private void updateListItem(int postion,Data mData){
    int visiblePosition = list_one.getFirstVisiblePosition();
    View v = list_one.getChildAt(postion - visiblePosition);
    ImageView img = (ImageView) v.findViewById(R.id.img_icon);
    TextView tv = (TextView) v.findViewById(R.id.txt_content);
    img.setImageResource(mData.getImgId());
    tv.setText(mData.getContent());
}

后來和群里的朋友討論了下,發(fā)現(xiàn)自己錯了

notifyDataSetChanged()方法會判斷是否需要重新渲染,如果當(dāng)前item沒有必要重新渲染 是不會重新渲染的,如果某個Item的狀態(tài)發(fā)生改變,都會導(dǎo)致View的重繪,而重繪的并不是 所有的Item,而是View狀態(tài)發(fā)生變化的那個Item!所以我們直接notifyDataSetChange()方法 即可,當(dāng)然知道多一個上面的方法也沒什么~


代碼下載:

ListViewDemo3.zip


本節(jié)小結(jié):

好的,本節(jié)跟大家講述了ListView中數(shù)據(jù)更新的實現(xiàn),當(dāng)然不止ListView,其他的Adapter 類控件都可以調(diào)用這些方法來完成數(shù)據(jù)更新~就說這么多吧~謝謝


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號