編輯:Android 技術基礎
前面我們已經掌握了 ListView 的基本用法,但你也許發現了:示例裡的數據都是寫死的靜態數據。可現實開發中,數據往往是動態變化的——新增了一條、刪掉了某一項,列表就應該跟著刷新。這一節我們就來聊聊 ListView 的數據更新,既包括整體刷新,也包括只更新其中一項。
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_main.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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="https://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 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); }
運行起來會發現頁面空空如也,白茫茫一片,用戶體驗並不好。這時可以調用 ListView 的 setEmptyView(View) 方法,在沒有數據時顯示一個自定義的 View。不過這個方法有點古怪:動態 new 出來的 View 塞進去往往不生效,必須在布局文件裡事先寫好;而且它設置的 View 加載時還常常不顯示,頗為靈異。比如這裡我們放一個提示「暫無數據」的 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("暫無數據~"); list_one.setEmptyView(txt_empty);
另一種更可控的做法是:定義一個和 ListView 同樣大小的布局,默認設 android:visibility="gone",然後在 Java 代碼裡判斷 mData 的 size,等於 0 就把這個布局顯示出來,有數據時再把它藏起來。
先加個按鈕,每按一次就往列表裡塞一條數據。
運行效果圖:
代碼實現
在自定義 BaseAdapter 裡加一個方法:
public void add(Data data) { if (mData == null) { mData = new LinkedList<>(); } mData.add(data); notifyDataSetChanged(); }
布局裡擺個按鈕並綁定事件:
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; } }
想插入到指定位置也行,在 Adapter 裡再寫一個帶 index 的方法:
//往特定位置,添加一個元素 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;
運行效果圖:
可以看到原本第九項的數據被插到了第五個位置。
同樣寫兩個方法,一個按對象刪,一個按游標刪:
public void remove(Data data) { if(mData != null) { mData.remove(data); } notifyDataSetChanged(); } public void remove(int position) { if(mData != null) { mData.remove(position); } notifyDataSetChanged(); }
再加兩個按鈕調用:
case R.id.btn_remove: mAdapter.remove(mData_5); break; case R.id.btn_remove2: mAdapter.remove(2); break;
運行效果圖:

可以看到第五項被移除了;而點擊按游標刪除時,一直刪的是第三項。
這個最簡單,直接調 clear 方法即可:
public void clear() { if(mData != null) { mData.clear(); } notifyDataSetChanged(); }
你可能注意到,每次改動數據後都會調用 notifyDataSetChanged()。一開始我以為:
notifyDataSetChanged() 會把界面上所有 item 重繪一遍,數據量一大豈不是影響性能?只改一項卻重繪全部,太不合理了。於是我用了個「傻辦法」——直接拿到那個 Item 的 View 去改控件:
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()); }
後來和群裡的朋友一討論,才發現自己想多了:
notifyDataSetChanged() 內部會判斷哪些 item 需要重新渲染,並不是無腦全刷。只有狀態真正發生改變的那個 Item 才會重繪,其他沒變的並不受影響。所以直接調 notifyDataSetChanged() 就好。當然,多知道上面那個手動刷新的方法也沒壞處。
ListViewDemo3.zip
這一節講了 ListView 數據更新的實現,其實不止 ListView,其他基於 Adapter 的控件也可以用這套方法完成數據刷新。就聊到這裡,謝謝~
SQLite 進階:事務、二進位資料與版本升級
資料庫事務SQLite 事務可把多個資料庫操作視為一個整體,全部成功才提交,否則回滾。資料庫目錄中的 journal 檔就是為了支援這類機制而產生。儲存二進位資料雖然實務
AudioManager 實戰:用三個按鈕切換鈴聲、靜音與震動(從零開始學 Android)
手機的聲音模式不外乎鈴聲、靜音、震動,或者震動加鈴聲。這些看似理所當然的行為,在 Android 裡其實都收攏到一個系統服務上——AudioManager。掌握它,你就能
Canvas API 詳解(Part 1):translate、rotate、scale、skew 與圖層管理
本節引言: 前面我們花了 13 小節詳細講解了 Android 中 Paint 類大部分常用的 API,從本節開始,我們來研究 Canvas(畫板)的一些常用 API。我
ContentProvider 入門:讀取系統資料與自訂內容提供者
ContentProvider 的作用ContentProvider 是 Android 四大元件之一,主要用於在不同應用程式之間安全地共用資料。它可以用來讀取聯絡人、簡