編輯:關於 Android 程式設計
上一篇拆解了 ListView 分組與字母索引導航的實作思路,並逐步完成了全部功能。但仔細檢視會發現設計上有兩個明顯缺陷:
這篇針對兩點做重構:先把功能抽成通用的 Activity,再對程式碼進行拆分與解耦。
原設計最大的問題是「污染」原有的 Bo——為了排序與產生分組標籤,硬加上拼音快取、標籤標記等欄位。
public class TestBo {
/** 主要欄位 */
private String boStr = null;
/** bo 拼音快取 */
private String boPinYin = null;
/** Bo 標籤標記 */
private String boTagFlag = null;
public TestBo() { super(); }
public TestBo(String str) { super(); this.boStr = str; }
public String getBoStr() { return boStr; }
public void setBoStr(String boStr) { this.boStr = boStr; }
public String getSortStrPinyin() { return boPinYin; }
public void setSortStrPinYin(String pinyin) { this.boPinYin = pinyin; }
public void setTag(String tag) { this.boTagFlag = tag; }
public String getTag() { return boTagFlag; }
}
真正有用的其實只有 boStr。產生列表時,本質上只需要知道「依哪個欄位分組」即可。這自然指向接口:讓 Bo 實作一個接口,由接口方法回傳作為排序依據的值。
public interface BoSort {
/** 取得作為索引依據的字串 */
public String getSortStr();
/** 取得索引字串的拼音,建議做快取 */
public String getSortStrPinyin();
/** 設定拼音快取 */
public void setSortStrPinYin(String pinyin);
/** 設定標籤,需要快取 */
public void setTag(String tag);
/** 取得標籤,回傳 null 代表不是標籤列 */
public String getTag();
}
Bo 只要實作這個接口即可。為了避免每個 Bo 都重複寫拼音與標籤的樣板程式,再提供一個抽象類作為預設實作,Bo 繼承它並只需實作 getSortStr():
/** 只需實作 getSortStr,其他不必修改 */
public abstract class DefaultBoSortImp implements BoSort {
private String boPinYin = null;
private String boTagFlag = null;
/** 一定要有這個建構子,後續反射會用到 */
public DefaultBoSortImp() { super(); }
@Override public String getSortStrPinyin() { return boPinYin; }
@Override public void setSortStrPinYin(String pinyin) { this.boPinYin = pinyin; }
@Override public void setTag(String tag) { this.boTagFlag = tag; }
@Override public String getTag() { return boTagFlag; }
}
整體流程與先前類似,差別在於資料處理被抽成獨立類別,且只依賴 BoSort 接口而非具體 Bo。建立標籤物件時改用反射,耦合度明顯降低。
public class RulerUtil {
/** 列表索引 */
public static final String[] indexStr = { "#", "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
public static final char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
/** 排序並插入分組標籤,同時記錄每個標籤在清單中的位置 */
public static ArrayList<BoSort> genSortedDataAndTagLocation(
List<? extends BoSort> myData,
HashMap<String, Integer> tagLocation)
throws InstantiationException, IllegalAccessException {
ArrayList<BoSort> res = new ArrayList<BoSort>();
res.addAll(myData);
// 依拼音首字母排序
Collections.sort(res, new Comparator<BoSort>() {
@Override
public int compare(BoSort lhs, BoSort rhs) {
char firChar = checkAndGetPinyin(lhs);
char secChar = checkAndGetPinyin(rhs);
if (firChar < secChar) return -1;
else if (firChar > secChar) return 1;
else return 0;
}
});
int size = res.size();
char nowTag = '\0';
for (int i = 0; i < size; i++) {
BoSort temp = res.get(i);
char tempTag = checkAndGetPinyin(temp);
if (Arrays.binarySearch(letters, tempTag) < 0) {
tempTag = '#'; // 非字母歸入 # 分組
}
if (nowTag != tempTag) {
// 用反射建立與資料同類型的標籤物件
Class<? extends BoSort> boClass = temp.getClass();
BoSort tagBO = boClass.newInstance();
tagBO.setTag(tempTag + "");
res.add(i, tagBO);
tagLocation.put(tempTag + "", i);
i++;
size++;
nowTag = tempTag;
}
}
tagLocation.put("#", 0);
return res;
}
/** 取得拼音首字母,沒有快取時即時轉換 */
private static char checkAndGetPinyin(BoSort bo) {
String pinyinStr = bo.getSortStrPinyin();
if (pinyinStr == null) {
bo.setSortStrPinYin(HanziToPinyin.getPinYin(bo.getSortStr()).toUpperCase());
pinyinStr = bo.getSortStrPinyin();
}
if (pinyinStr != null && pinyinStr.length() >= 1) {
return pinyinStr.charAt(0);
}
return '\0';
}
}
Adapter 的實作與先前相同,只是同樣只依賴接口。Activity 層則抽出一個抽象基底類,需要分組導航時繼承它並實作回傳資料的方法即可。右側的字母索引先被獨立成一個可於 XML 中直接使用的 View。
這個自訂 View 在初始化時依 indexStr 動態產生字母,並處理觸摸事件換算成索引位置,透過 OnRulerTouch 回呼對外溝通:
/** 右側尺子導航,需呼叫 setOnRulerTouch 設定回呼 */
public class RulerWidget extends LinearLayout {
private static final int INDEX_LENGTH = RulerUtil.indexStr.length;
public RulerWidget(Context context) { super(context); init(); }
public RulerWidget(Context context, AttributeSet attrs) { super(context, attrs); init(); }
public RulerWidget(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); init();
}
private void init() {
int color = getResources().getColor(R.color.g_ruler_letter_color);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
this.bringToFront();
params.weight = 1;
for (int i = 0; i < RulerUtil.indexStr.length; i++) {
final TextView tv = new TextView(getContext());
tv.setLayoutParams(params);
tv.setTextColor(color);
tv.setGravity(Gravity.CENTER);
tv.setText(RulerUtil.indexStr[i]);
this.addView(tv);
}
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int height = v.getHeight();
float pos = event.getY();
int sectionPosition = (int) ((pos / height) / (1f / INDEX_LENGTH));
if (sectionPosition < 0) sectionPosition = 0;
else if (sectionPosition > INDEX_LENGTH - 1) sectionPosition = INDEX_LENGTH - 1;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (onRulerTouch != null) onRulerTouch.onDown(sectionPosition);
RulerWidget.this.setBackgroundResource(R.color.g_ruler_selected);
break;
case MotionEvent.ACTION_MOVE:
if (onRulerTouch != null) onRulerTouch.onMove(sectionPosition);
break;
default:
if (onRulerTouch != null) onRulerTouch.onOthers();
RulerWidget.this.setBackgroundResource(R.color.g_blank);
}
return true;
}
});
}
private OnRulerTouch onRulerTouch;
public void setOnRulerTouch(OnRulerTouch onRulerTouch) {
this.onRulerTouch = onRulerTouch;
}
}
/** ruler 觸摸回呼 */
public interface OnRulerTouch {
public void onDown(int position);
public void onMove(int position);
public void onUP();
public void onOthers();
}
子類別只需實作 public abstract List<? extends BoSort> getDataList();。資料載入放在 AsyncTask 中,完成後交給 handleSuccessData() 綁定 Adapter 與回呼:
public abstract class RulerActivity extends Activity {
protected TextView noDataView;
protected TextView RulerTag;
protected ProgressBarWithText progress;
protected ListView listView;
protected RulerWidget ruler;
private RulerAdapter rulerAdapter;
private List<? extends BoSort> originalList;
private List<BoSort> dealedList;
private HashMap<String, Integer> tagLocation = new HashMap<String, Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.g_ruler);
findView();
initView();
initData();
}
private void findView() {
noDataView = (TextView) findViewById(R.id.g_base_list_nodata);
RulerTag = (TextView) findViewById(R.id.g_ruler_tag);
progress = (ProgressBarWithText) findViewById(R.id.g_base_progressbar_withtext);
listView = (ListView) findViewById(R.id.g_base_list);
ruler = (RulerWidget) findViewById(R.id.g_ruler);
}
private void initView() {
progress.setVisibility(View.VISIBLE);
RulerTag.setVisibility(View.GONE);
noDataView.setVisibility(View.GONE);
listView.setVisibility(View.GONE);
ruler.setVisibility(View.GONE);
}
private void initData() {
new GetDataAsyTask().execute();
}
/** 子類別實作此方法提供原始資料 */
public abstract List<? extends BoSort> getDataList();
private void handleSuccessData() {
listView.setVisibility(View.VISIBLE);
ruler.setVisibility(View.VISIBLE);
rulerAdapter = new RulerAdapter(dealedList, this);
ruler.setOnRulerTouch(new OnRulerTouch() {
@Override public void onUP() { }
@Override public void onOthers() { RulerTag.setVisibility(View.GONE); }
@Override public void onMove(int position) {
RulerTag.setText(RulerUtil.indexStr[position]);
listView.setSelection(getPosition(position));
}
@Override public void onDown(int position) {
RulerTag.setVisibility(View.VISIBLE);
RulerTag.setText(RulerUtil.indexStr[position]);
listView.setSelection(getPosition(position));
}
});
listView.setAdapter(rulerAdapter);
rulerAdapter.notifyDataSetChanged();
}
/**
* 取得觸摸字母時列表應滾動到的位置。
* 若該字母沒有對應標籤,則往後尋找下一個存在的標籤。
*/
private Integer getPosition(final int j) {
Integer pos = null;
int i = j;
while (pos == null && i <= RulerUtil.indexStr.length - 1) {
pos = tagLocation.get(RulerUtil.indexStr[i]);
i++;
}
if (pos == null) pos = dealedList.size() - 1;
return pos;
}
class GetDataAsyTask extends AsyncTask<Void, Void, Void> {
@Override protected void onPreExecute() {
super.onPreExecute();
progress.setVisibility(View.VISIBLE);
}
@Override protected Void doInBackground(Void... params) {
originalList = getDataList();
try {
dealedList = RulerUtil.genSortedDataAndTagLocation(originalList, tagLocation);
} catch (Exception e) {
e.printStackTrace();
if (dealedList != null) { dealedList.clear(); dealedList = null; }
if (originalList != null) { originalList.clear(); originalList = null; }
if (tagLocation != null) { tagLocation.clear(); tagLocation = null; }
}
return null;
}
@Override protected void onPostExecute(Void result) {
progress.setVisibility(View.GONE);
super.onPostExecute(result);
if (dealedList == null) {
noDataView.setVisibility(View.VISIBLE);
return;
}
handleSuccessData();
}
}
}
重構到此完成。整組設計的價值在於:Bo 不再被額外欄位污染,資料處理與 UI 各自獨立,而新增一個需要分組導航的頁面時,只要繼承 RulerActivity 並實作 getDataList() 就好。
Android 底部 Tab 架構設計:主流界面風格分析
底部 Tab 為何常見 行動裝置螢幕有限,底部 Tab 能在不遮擋主要內容的情況下,提供快速切換入口。常見設計會兼顧可點擊區域、圖示辨識性與目前選取狀態。 風格一:背景不
MPAndroidChart 折線圖實作詳解:初始化、資料設定與更新
MPAndroidChart 是 Android 上常用的圖表庫,支援折線圖、長條圖、圓餅圖等多種圖表。本文以折線圖為例,說明初始化、資料設定、更新與 x 軸資料處理方式
微信朋友圈怎麼發純文字?彩色文字玩法解析
朋友圈通常預設只能發圖文,但其實只要長按相機按鈕,就能發表純文字。 發純文字 進入朋友圈後,長按右上角相機圖示約 2 至 3 秒,畫面會跳出文字輸入框,輸入內容後即可發
自定義 View 完全指南:測量、佈局與繪製
在 Android 開發中,自定義 View 幾乎是每個開發者都會遇到的進階主題。當系統自帶控件無法滿足業務需求時,我們就需要自己動手實現一個 View。要真正掌握自定義