Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ListView 分組與字母索引導航重構筆記(二):用接口解耦

編輯:關於 Android 程式設計

上一篇拆解了 ListView 分組與字母索引導航的實作思路,並逐步完成了全部功能。但仔細檢視會發現設計上有兩個明顯缺陷:

  1. 布局的通用性不足,而且必須在 Bo 中塞入額外欄位,這些欄位本身沒有業務意義。
  2. 所有邏輯都堆在 Activity 裡。

這篇針對兩點做重構:先把功能抽成通用的 Activity,再對程式碼進行拆分與解耦。

一、思路:別再污染 Bo

原設計最大的問題是「污染」原有的 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 實作一個接口,由接口方法回傳作為排序依據的值。

二、重構 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 層

Adapter 的實作與先前相同,只是同樣只依賴接口。Activity 層則抽出一個抽象基底類,需要分組導航時繼承它並實作回傳資料的方法即可。右側的字母索引先被獨立成一個可於 XML 中直接使用的 View。

1. RulerWidget

這個自訂 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();
}

2. 抽象 RulerActivity

子類別只需實作 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() 就好。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved