編輯:關於 Android 程式設計
ListView 的優化核心只有兩個詞:復用與異步。前者靠 convertView 和 ViewHolder 模式避免重複創建視圖,後者靠子線程把數據準備好再刷新界面。本文以一組完整的示例代碼說明這套做法,同時附上分頁加載與擴展列表的用法。
關鍵點在 getView():如果 convertView 不為空,就直接復用並從 tag 中取出控件引用,跳過漫長的 findViewById();只有第一次創建時才 inflate 布局並把控件引用存進 tag。
/**
* 待處理請假信息的數據適配器類
*/
private class LeaveInfoAdapter extends BaseAdapter {
@Override
public int getCount() {
return mleaveInfos.size();
}
@Override
public Object getItem(int position) {
return mleaveInfos.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
ViewHolder holder = null;
// 有可復用的視圖,直接取;否則重新創建
if (convertView != null && convertView instanceof LinearLayout) {
view = convertView;
holder = (ViewHolder) view.getTag();
} else {
view = View.inflate(getApplicationContext(), R.layout.leave_info_item, null);
holder = new ViewHolder();
holder.name = (TextView) view.findViewById(R.id.tv_name);
holder.workIdAndDepartment = (TextView) view.findViewById(R.id.tv_workid_depart);
holder.leaveinfo = (TextView) view.findViewById(R.id.tv_leave_info);
holder.date = (TextView) view.findViewById(R.id.tv_date);
holder.endDate = (TextView) view.findViewById(R.id.tv_endtime);
view.setTag(holder);
}
LeaveInfo info = mleaveInfos.get(position);
holder.name.setText(info.getName());
holder.workIdAndDepartment.setText("(工號:" + info.getWorkId() + " 部門:" + info.getDepartment() + ")");
holder.leaveinfo.setText(info.getLeaveInfo());
holder.date.setText("假期起止:" + info.getLeaveData() + "\n");
holder.endDate.setText("-" + info.getEndleaveDate());
return view;
}
}
private static class ViewHolder {
TextView name; // 員工姓名
TextView workIdAndDepartment; // 工號和部門
TextView leaveinfo; // 請假信息
TextView date; // 請假日期
TextView endDate;
}
這裡有兩個容易忽略的細節:ViewHolder 聲明為 static 內部類,可以避免持有外部 Activity 的隱式引用,減少內存洩漏風險;判斷復用條件時用 instanceof LinearLayout 而非直接 != null,是為了防止 ListView 混用多種 item 布局時取到錯誤的視圖。
leave_info_item.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="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv_headcolor"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:src="@drawable/light_green" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp" >
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名"
android:textColor="#ff0000"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_leave_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_name"
android:paddingTop="8dp"
android:text="請假理由"
android:textSize="20sp" />
<TextView
android:id="@+id/tv_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/tv_leave_info"
android:layout_alignParentRight="true"
android:text="日期"
android:textColor="#000000"
android:textSize="10sp" />
<TextView
android:id="@+id/tv_endtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_date"
android:layout_alignParentRight="true"
android:text="日期2"
android:textColor="#000000"
android:textSize="10sp" />
<TextView
android:id="@+id/tv_workid_depart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/tv_name"
android:gravity="center_horizontal"
android:paddingLeft="5dp"
android:text="姓名和部門"
android:textColor="#0000ff"
android:textSize="13sp" />
</RelativeLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@android:drawable/divider_horizontal_dark" />
</LinearLayout>
數據讀取放在 doInBackground(),完成後在 onPostExecute() 中更新界面。這裡還順帶處理了首次設置適配器與後續刷新的差異:
/**
* 使用異步任務加載數據,填充待處理請假信息 ListView
*/
private void fillData() {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void result) {
if (mAdapter == null) {
mAdapter = new LeaveInfoAdapter();
mLVleaveInfos.setAdapter(mAdapter);
Log.i("測試", "異步任務顯示後台獲得數據庫數據");
} else {
mAdapter.notifyDataSetChanged(); // 只刷新,不重建適配器
}
super.onPostExecute(result);
}
@Override
protected Void doInBackground(Void... params) {
mleaveInfos = mLeaveInfosDao.findAll();
if (mleaveInfos == null) {
Toast.makeText(HomeActivity.this, "請假數據不存在或是已經清除!", 500).show();
}
Log.i("測試", "異步任務後台獲得數據庫數據" + mleaveInfos.size());
return null;
}
}.execute();
}
順帶提醒:doInBackground() 中不要直接彈 Toast,那是子線程,必須通過 Handler 或 onPostExecute() 回到主線程;另外新版 Android 已不建議使用 AsyncTask,改用線程池加 Handler、或 Kotlin 協程更合適。
mLVleaveInfos.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object object = mLVleaveInfos.getItemAtPosition(position);
if (object instanceof LeaveInfo) {
tmpInfo = (LeaveInfo) object;
showAcceptOrNo();
}
}
});
本地數據量小,一次性加載即可;但服務器端數據應該分頁拉取,既省流量也保證流暢。做法是在滾動狀態變化時判斷是否已到達末尾:
// 下拉列表空閒時判斷是否需要加載下一頁
mRubishSms.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:
int position = mRubishSms.getLastVisiblePosition();
int total = 0;
if (mInfos != null) {
total = mInfos.size();
}
if (position == total - 1) {
offset += maxNum;
if (offset > totalNums) {
Toast.makeText(RubishSmsActivity.this, "數據已經加載完,沒有更多的數據了...", 300).show();
return;
}
fillData();
}
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) { }
});
為什麼判斷 SCROLL_STATE_IDLE 而不是滑動過程中?因為手指滑動時會連續觸發回調,若不加限制會導致重複發起請求。等列表停下來再判斷,既能避免重複,也能保證用戶看清最後一項。
列表項的具體操作(刪除、恢復、加入黑名單等)通過一個自定義 Dialog 呈現:
mRubishSms.setOnItemClickListener(new OnItemClickListener() {
View m_view = View.inflate(RubishSmsActivity.this, R.layout.show_rubish_sms_operation, null);
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object object = mRubishSms.getItemAtPosition(position);
if (object instanceof RubishSmsInfo) {
final RubishSmsInfo info = (RubishSmsInfo) object;
Dialog builder = new Dialog(RubishSmsActivity.this);
builder.setTitle("提示");
builder.setContentView(m_view);
// 刪除
((TextView) m_view.findViewById(R.id.tv_delete)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mInfos.remove(info);
if (mRubishSmsInfoDao == null) {
mRubishSmsInfoDao = new RubishSmsInfoDao(getApplicationContext());
}
mRubishSmsInfoDao.deleteSmsInfos(info);
if (mAdapter == null) {
mAdapter = new RubishSmsInfosAdapter();
mRubishSms.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
}
});
builder.show();
}
}
});
分組列表同樣適用復用思路,這裡額外示範了用 Map 緩存每組的子項數據,避免反覆查庫:
public class CommonNumberActivity extends Activity {
private ExpandableListView elv;
private List<String> groupNames;
private Map<Integer, List<String>> childrenCacheInfos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
childrenCacheInfos = new HashMap<Integer, List<String>>();
setContentView(R.layout.activity_common_num);
elv = (ExpandableListView) findViewById(R.id.elv);
elv.setAdapter(new MyAdapter());
elv.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_DIAL);
String number = childrenCacheInfos.get(groupPosition)
.get(childPosition).split("\n")[1];
intent.setData(Uri.parse("tel:" + number));
startActivity(intent);
return false;
}
});
}
private class MyAdapter extends BaseExpandableListAdapter {
@Override
public int getGroupCount() {
groupNames = CommonNumDao.getGroupInfos();
return groupNames.size();
}
@Override
public int getChildrenCount(int groupPosition) {
List<String> childreninfos;
if (childrenCacheInfos.containsKey(groupPosition)) {
childreninfos = childrenCacheInfos.get(groupPosition);
} else {
childreninfos = CommonNumDao.getChildrenInfosByPosition(groupPosition);
childrenCacheInfos.put(groupPosition, childreninfos);
}
return childreninfos.size();
}
@Override public Object getGroup(int groupPosition) { return null; }
@Override public Object getChild(int groupPosition, int childPosition) { return null; }
@Override public long getGroupId(int groupPosition) { return 0; }
@Override public long getChildId(int groupPosition, int childPosition) { return 0; }
@Override public boolean hasStableIds() { return false; }
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
TextView tv;
if (convertView != null && convertView instanceof TextView) {
tv = (TextView) convertView;
} else {
tv = new TextView(getApplicationContext());
}
tv.setTextSize(25);
tv.setTextColor(Color.RED);
tv.setText(" " + groupNames.get(groupPosition));
return tv;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
TextView tv;
if (convertView != null && convertView instanceof TextView) {
tv = (TextView) convertView;
} else {
tv = new TextView(getApplicationContext());
}
tv.setTextSize(18);
tv.setTextColor(Color.BLUE);
tv.setText(childrenCacheInfos.get(groupPosition).get(childPosition));
return tv;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
BaseAdapter 並不只服務於 ListView,GridView 同樣適用:
public class OftenUseFunctionActivity extends Activity {
private boolean D = true;
private GridView mGridView;
private GVAdapter mAdapter;
private String[] items = {"清理加速", "話費流量", "騷擾攔截", "防吸費", "支付保镖", "手機殺毒"};
private int[] icons = {
R.drawable.exam_frequently_used_tools_icon_clean,
R.drawable.exam_frequently_used_tools_icon_net_traffic,
R.drawable.exam_frequently_used_tools_icon_block_anoy,
R.drawable.exam_frequently_used_tools_icon_costguard,
R.drawable.exam_frequently_used_tools_icon_guardpay,
R.drawable.exam_frequently_used_tools_icon_malware
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_often_use_function);
mGridView = (GridView) this.findViewById(R.id.gv_home);
mAdapter = new GVAdapter();
mGridView.setAdapter(mAdapter);
setListener();
}
private void setListener() {
mGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
startActivity(new Intent(OftenUseFunctionActivity.this, CleanCacheActivity.class));
break;
case 1:
if (D) Log.i("OftenUseFunctionActivity", "話費流量");
break;
case 2:
startActivity(new Intent(OftenUseFunctionActivity.this, StopAnonyActivity.class));
break;
case 3:
if (D) Log.i("OftenUseFunctionActivity", "防吸費");
break;
case 4:
if (D) Log.i("OftenUseFunctionActivity", "支付保镖");
break;
case 5:
startActivity(new Intent(OftenUseFunctionActivity.this, KillVirusActivity.class));
break;
}
}
});
}
private class GVAdapter extends BaseAdapter {
@Override public int getCount() { return items.length; }
@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) {
// 這裡也可以加上 convertView 復用與 ViewHolder
View view = View.inflate(OftenUseFunctionActivity.this, R.layout.home_item, null);
ImageView ivIcon = (ImageView) view.findViewById(R.id.iv_home_icon);
TextView tvFunName = (TextView) view.findViewById(R.id.tv_home_function_name);
ivIcon.setImageResource(icons[position]);
tvFunName.setText(items[position]);
return view;
}
}
}
對應的 home_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="95dp"
android:gravity="center"
android:background="@drawable/grid_selector" >
<ImageView
android:layout_marginTop="5dp"
android:id="@+id/iv_home_icon"
android:layout_width="55dp"
android:layout_height="45dp" />
<TextView
android:layout_marginTop="5dp"
android:id="@+id/tv_home_function_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="center_vertical"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
把上面分散的技巧收攏一下,ListView 優化可以歸納為:
android:layout_height,讓系統提前分配空間;getView() 中不要做耗時計算、不要打印日誌、不要創建對象。如果列表結構複雜、或者需要更好的內存與流暢度表現,可以考慮直接遷移到 RecyclerView——它內置了 ViewHolder 強制模式、支持局部刷新(notifyItemChanged 配合 DiffUtil),並提供了多種 LayoutManager,是 ListView 的現代替代方案。
Android 智能指針淺析:從 LightRefBase 到 RefBase
長期以來,C++ 的記憶體管理一直令人頭痛:空指標、野指標、記憶體洩漏……C++ 工程師看到這些字眼就頭皮發麻。更麻煩的是,當程式架構龐大或複雜時,這類問題往往極難排查。
Android 開發系列(二十):AutoCompleteTextView 自動完成文本框的用法
當使用者輸入一定的字元後,自動完成文本框會顯示一個下拉選單供使用者選擇;一旦選中某個選項,AutoCompleteTextView 就會依使用者的選擇自動把內容填入文本框
Android 百度地圖開發系列:地圖初始化與定位功能實作
在 Android 應用中,地圖功能的使用頻率相當高。回顧過去寫過的專案和用過的百度地圖 API,這裡整理一份從零開始實作 Android 百度地圖的完整流程,第一篇聚焦
把自己寫的 Android 庫發布到 JCenter:完整流程與踩坑記錄
寫了一個自己覺得還不錯的組件,與其躺在本地硬盤裡,不如開源出去讓更多人用。這篇記錄把 Android Library 發布到 JCenter 的完整流程,包含每一步的配置