編輯:關於 Android 程式設計
專案裡常會遇到這類需求:列表要能勾選、要能全選、要在同一行裡做單選,甚至每一列都要填幾個數字並即時加總。功能本身都不算難,真正的坑在列表項視圖復用導致的狀態錯亂。這一篇把幾種常見寫法一次整理清楚。
關鍵是用一個集合記錄「第幾列被勾選」,並在 getView 裡每次都依集合內容重設 CheckBox 狀態,而不是依賴 convertView 上的舊狀態。
class BatchAdpter extends BaseAdapter {
private HashMap<Integer, Boolean> isSelected; // 管理勾選狀態
private List<DtGzsCustomer> list;
private Context context;
@SuppressLint("UseSparseArrays")
public BatchAdpter(List<DtGzsCustomer> list, Context context) {
this.context = context;
this.list = new ArrayList<>();
if (list != null) {
this.list.addAll(list);
}
isSelected = new HashMap<>();
initDate(false); // 預設全不選
}
/** 依傳入的布林值,批次設定所有列的勾選狀態 */
private void initDate(boolean bool) {
for (int i = 0; i < list.size(); i++) {
DtGzsCustomer dtGzsCustomer = list.get(i);
if (bool) {
datas.add(dtGzsCustomer.thread_id);
} else {
datas.remove(dtGzsCustomer.thread_id);
}
getIsSelected().put(i, bool);
}
}
public HashMap<Integer, Boolean> getIsSelected() {
return isSelected;
}
public void setIsSelected(HashMap<Integer, Boolean> isSelected) {
this.isSelected = isSelected;
}
public void nodfiyData(List<DtGzsCustomer> list) {
if (list != null) {
this.list.clear();
this.list.addAll(list);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = View.inflate(context, R.layout.no_contact_listview_item, null);
holder.name = convertView.findViewById(R.id.name);
holder.sex = convertView.findViewById(R.id.sex);
holder.popuse = convertView.findViewById(R.id.popuse);
holder.tv_phone = convertView.findViewById(R.id.tv_phone);
holder.allocation = convertView.findViewById(R.id.allocation);
holder.time = convertView.findViewById(R.id.time);
holder.btn_dis = convertView.findViewById(R.id.btn_dis);
holder.btn_allot = convertView.findViewById(R.id.btn_allot);
holder.btn_telephone = convertView.findViewById(R.id.btn_telephone);
holder.btn_follow = convertView.findViewById(R.id.btn_follow);
holder.cb = convertView.findViewById(R.id.cb);
holder.allocation.setVisibility(View.INVISIBLE);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
DtGzsCustomer data = list.get(position);
SalesTools.setTextViewText(holder.name, data.p_customer_name);
SalesTools.setTextViewText(holder.sex, data.gender);
SalesTools.setTextViewText(holder.popuse, data.purpose_series);
SalesTools.setTextViewText(holder.tv_phone, data.mobile_no);
SalesTools.setTextViewText(holder.allocation, data.thread_contact_state);
SalesTools.setTextViewText(holder.time, data.thread_create_date);
holder.btn_dis.setVisibility(View.INVISIBLE);
holder.btn_allot.setVisibility(View.INVISIBLE);
holder.btn_telephone.setVisibility(View.INVISIBLE);
holder.btn_follow.setVisibility(View.INVISIBLE);
holder.cb.setVisibility(View.VISIBLE);
// 每次繪製都依集合重設狀態,這一步是避免復用錯亂的關鍵
HashMap<Integer, Boolean> isSelected2 = getIsSelected();
Boolean checked = isSelected2.get(position);
holder.cb.setChecked(checked != null && checked);
return convertView;
}
static class ViewHolder {
TextView name, sex, popuse, tv_phone, allocation, time;
Button btn_dis, btn_allot, btn_telephone, btn_follow;
CheckBox cb;
}
}
全選就是呼叫 initDate(true),再把計數設為列表長度並刷新:
// 全選
private void choiceAll() {
adapter.initDate(true);
checkNum = list.size(); // 數量設為 list 的長度
cb_all.setTextColor(Color.parseColor("#0097e0"));
dataChanged();
}
單列點擊時,直接從 ViewHolder 取 CheckBox,省掉一層層 findViewById:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DtGzsCustomer dtGzsCustomer = list.get(position);
// 直接取出 ViewHolder,省去反覆 findViewById
ViewHolder holder = (ViewHolder) view.getTag();
holder.cb.toggle();
// 把狀態記回集合
adapter.getIsSelected().put(position, holder.cb.isChecked());
if (holder.cb.isChecked()) {
checkNum++;
if (checkNum == list.size()) { // 全部勾上,連帶全選鈕亮燈
cb_all.setChecked(true);
cb_all.setTextColor(Color.parseColor("#0097e0"));
}
datas.add(dtGzsCustomer.thread_id);
} else {
cb_all.setChecked(false);
cb_all.setTextColor(Color.parseColor("#c0c0c0"));
checkNum--;
datas.remove(dtGzsCustomer.thread_id);
}
dataChanged();
}
簽到場景很常見:每一列有「到崗 / 遲到 / 休假 / 曠工」四個單選鈕,彼此互斥,但不同列之間互不影響。做法是透過 OnCheckedChangeListener 把選擇寫進資料物件本身,再由資料物件的四個布林欄位回寫控制項:
class CheckAdapter extends BaseAdapter {
private Context mContext;
private List<DtGzsSchedule> list;
public CheckAdapter(Context context, List<DtGzsSchedule> list) {
this.mContext = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext)
.inflate(R.layout.check_listview_item, parent, false);
holder.sale_name = convertView.findViewById(R.id.sale_name);
holder.sale_branch = convertView.findViewById(R.id.sale_branch);
holder.scb = convertView.findViewById(R.id.scb);
holder.scc = convertView.findViewById(R.id.scc);
holder.scd = convertView.findViewById(R.id.scd);
holder.sce = convertView.findViewById(R.id.sce);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final DtGzsSchedule dtGzsSchedule = list.get(position);
OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) return;
String choice = buttonView.getText().toString();
if ("到崗".equals(choice)) {
dtGzsSchedule.check_type = "0";
} else if ("遲到".equals(choice)) {
dtGzsSchedule.check_type = "1";
} else if ("休假".equals(choice)) {
dtGzsSchedule.check_type = "2";
} else if ("曠工".equals(choice)) {
dtGzsSchedule.check_type = "3";
}
setActualNum();
}
};
holder.scb.setOnCheckedChangeListener(listener);
holder.scc.setOnCheckedChangeListener(listener);
holder.scd.setOnCheckedChangeListener(listener);
holder.sce.setOnCheckedChangeListener(listener);
holder.sale_name.setText("" + dtGzsSchedule.sales_consultant_name);
holder.sale_branch.setText("" + dtGzsSchedule.sales_branch);
// 依資料中的 check_type 還原四個按鈕的狀態
String check_type = dtGzsSchedule.check_type;
dtGzsSchedule.scbChecked = "0".equals(check_type);
dtGzsSchedule.sccChecked = "1".equals(check_type);
dtGzsSchedule.scdChecked = "2".equals(check_type);
dtGzsSchedule.sceChecked = "3".equals(check_type);
holder.scb.setChecked(dtGzsSchedule.scbChecked);
holder.scc.setChecked(dtGzsSchedule.sccChecked);
holder.scd.setChecked(dtGzsSchedule.scdChecked);
holder.sce.setChecked(dtGzsSchedule.sceChecked);
return convertView;
}
static class ViewHolder {
TextView sale_name, sale_branch;
RadioButton scb, scc, scd, sce;
}
}
兩層結構下做單選,思路和 ListView 一樣:記住被點選的 group 與 child 位置,在 getChildView 中比對並切換圖示。
class PinnedHeaderExpandableAdapter extends BaseExpandableListAdapter implements HeaderAdapter {
private Context context;
private PinnedHeaderExpandableListView listView;
private LayoutInflater inflater;
private Map<String, List<DtGzsCustomer>> map;
private List<String> parentList;
public PinnedHeaderExpandableAdapter(List<String> parentList,
Map<String, List<DtGzsCustomer>> map,
Context context,
PinnedHeaderExpandableListView listView) {
this.context = context;
this.listView = listView;
inflater = LayoutInflater.from(this.context);
this.map = new HashMap<>();
if (map != null) {
this.map.putAll(map);
}
this.parentList = new ArrayList<>();
if (parentList != null) {
this.parentList.addAll(parentList);
}
}
@Override
public int getChildrenCount(int groupPosition) {
if (groupPosition != -1) {
String key = parentList.get(groupPosition);
return map.get(key).size();
}
return 0;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
String key = parentList.get(groupPosition); // 用組名當 key 取 value
return map.get(key).get(childPosition).sales_consultant_name;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.child, null);
TextView text = convertView.findViewById(R.id.childto);
ImageView iv = convertView.findViewById(R.id.iv);
// 位置相同代表被選中,換成勾選圖示
if (group_groupId == groupPosition && child_childId == childPosition) {
iv.setImageResource(R.drawable.login_check);
} else {
iv.setImageResource(R.drawable.login_uncheck);
}
String key = parentList.get(groupPosition);
DtGzsCustomer childernItem = map.get(key).get(childPosition);
SalesTools.setTextViewText(text, childernItem.sales_consultant_name);
return convertView;
}
@Override
public Object getGroup(int groupPosition) {
return parentList.get(groupPosition);
}
@Override
public int getGroupCount() {
return parentList.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.group, null);
ImageView iv = convertView.findViewById(R.id.groupIcon);
TextView tv = convertView.findViewById(R.id.groupto);
iv.setImageResource(isExpanded ? R.drawable.btn_arrow_up : R.drawable.btn_arrow_down);
SalesTools.setTextViewText(tv, parentList.get(groupPosition));
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private SparseIntArray groupStatusMap = new SparseIntArray();
@Override
public void setGroupClickStatus(int groupPosition, int status) {
groupStatusMap.put(groupPosition, status);
}
@Override
public int getGroupClickStatus(int groupPosition) {
if (groupStatusMap.keyAt(groupPosition) >= 0) {
return groupStatusMap.get(groupPosition);
}
return 0;
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
子項點擊時記下被點的一、二級位置,再通知刷新:
// 子項目的點擊事件
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String key = groupData.get(groupPosition);
List<DtGzsCustomer> list = map.get(key);
DtGzsCustomer dtGzsCustomer = list.get(childPosition);
sales_consultant_name = dtGzsCustomer.sales_consultant_name;
sales_consultant_id = dtGzsCustomer.sales_consultant_id;
group_groupId = groupPosition;
child_childId = childPosition;
adapter.notifyDataSetChanged(); // 刷新介面
return true;
}
這一題最容易出問題:列表滾動時 EditText 會被復用,如果每次都無條件 addTextChangedListener,監聽器會越疊越多,輸入也會互相串台。解法是每次 getView 先移除舊監聽器,並用 setTag 保存當前監聽器:
class SetAdapter extends BaseAdapter {
private List<DtGzsCustomer> goalList;
private Context context;
public SetAdapter(Context context, List<DtGzsCustomer> goalList) {
this.context = context;
this.goalList = new ArrayList<>();
if (goalList != null) {
this.goalList.addAll(goalList);
}
}
public void nodfiyData(List<DtGzsCustomer> goalList) {
if (goalList != null) {
this.goalList.clear();
this.goalList.addAll(goalList);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return goalList.size();
}
@Override
public Object getItem(int position) {
return goalList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context)
.inflate(R.layout.serise_data_view, parent, false);
holder.et_order = convertView.findViewById(R.id.et_order);
holder.et_car = convertView.findViewById(R.id.et_car);
holder.sale_name = convertView.findViewById(R.id.sale_name);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// 隔行換色,讓長列表更容易讀
convertView.setBackgroundColor(position % 2 == 0
? Color.parseColor("#e4ebf1") : Color.parseColor("#ced7de"));
final DtGzsCustomer dtGzsCustomer = goalList.get(position);
// 復用前先摘掉舊監聽器,避免重複觸發
removeTextWatcher(holder.et_order);
removeTextWatcher(holder.et_car);
holder.et_order.setText("" + dtGzsCustomer.order_num);
holder.et_car.setText("" + dtGzsCustomer.return_num);
holder.sale_name.setText("" + dtGzsCustomer.sales_consultant_name);
TextWatcher orderTitle = new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable s) {
int sum = 0;
dtGzsCustomer.order_num = TextUtils.isEmpty(s) ? "" : String.valueOf(s);
String id = dtGzsCustomer.sales_consultant_id;
orderMap.remove(id);
orderMap.put(id, dtGzsCustomer.order_num);
Iterator<Map.Entry<String, String>> it = orderMap.entrySet().iterator();
while (it.hasNext()) {
String value = it.next().getValue();
if (value == null || value.length() == 0) {
value = "0";
}
sum += Integer.parseInt(value);
}
tv_order.setText("訂車" + sum + "台");
}
};
holder.et_order.addTextChangedListener(orderTitle);
holder.et_order.setTag(orderTitle);
TextWatcher carContent = new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable s) {
int sum = 0;
dtGzsCustomer.return_num = TextUtils.isEmpty(s) ? "" : String.valueOf(s);
String id = dtGzsCustomer.sales_consultant_id;
carMap.remove(id);
carMap.put(id, dtGzsCustomer.return_num);
Iterator<Map.Entry<String, String>> it = carMap.entrySet().iterator();
while (it.hasNext()) {
String value = it.next().getValue();
if (value == null || value.length() == 0) {
value = "0";
}
sum += Integer.parseInt(value);
}
tv_return.setText("交車" + sum + "台");
}
};
holder.et_car.addTextChangedListener(carContent);
holder.et_car.setTag(carContent);
return convertView;
}
/** 移除 TextWatcher */
private void removeTextWatcher(EditText editText) {
if (editText.getTag() instanceof TextWatcher) {
editText.removeTextChangedListener((TextWatcher) editText.getTag());
}
}
static class ViewHolder {
EditText et_order, et_car;
TextView sale_name;
}
}

把這幾段整理一下,其實只有三條原則:
如果今天重寫一次,這些樣板其實都可以交給 RecyclerView 加 DataBinding 或通用 Adapter 基類來收斂,但底層思路完全一致。
Android 性能與體驗優化實戰建議大全
開始 Android 開發有個好方法:找一些與目標功能相似的代碼,改一改讓它實現你想要的,遇到問題就去 Stack Overflow 求解。對每個想加的關鍵特性重複這一過
Android Scroller 原理與實作:打造 ListView 側滑菜單
在 Android 中,若直接使用 scrollTo 或 scrollBy 移動 View,過程通常是瞬間完成,使用者體驗較差。Scroller 的作用就是讓位移具備過渡
Android 官方文檔解讀:App Components 之 Fragment
Fragment 是 Android API 中的一個類,它代表 Activity 介面中的一個部分模組;你可以在同一個 Activity 中使用多個 Fragment,
Android Studio 常用快捷鍵整理
終於把卡頓到令人心煩的 Eclipse 丟掉了。用了一個月 Android Studio 之後,我對它的設計實在佩服——即便當時版本還停留在 0.4.5,功能已經相當完整