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

Android 列表分組與字母索引導航重構(二):用註解徹底解耦

編輯:關於 Android 程式設計

上一篇把 ListView 的分組與字母索引導航重構了一次,成果是新實作只依賴介面而非具體的 Bo。但仍有個小小的遺憾:原始的資料 Bo 必須自己實作介面或繼承抽象類。能不能再往前一步,讓 Bo 保持原樣、什麼都不用改?可以,答案是 Java 註解。

思路

Java 註解(又稱標註)提供了一套機制,讓我們能對方法、類、參數、套件、域與變數附加標準化的資訊,並在後續某個時點透過反射把這些資訊取出來使用。

分組列表重構後,剩下的唯一關鍵資訊是「用哪個欄位來分組排序」。只要用註解把這個資訊標記在 Bo 上,Bo 就不需要為了框架而實作任何介面。

另外,拼音之類的快取仍需保存,所以做法是:把原始 Bo 包裝一層,用泛型承接。下面逐步來。

定義註解與包裝類

註解只需標記依哪個欄位分組,並將保留策略設為運行時(這樣反射才讀得到):

@Target(ElementType.TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface RulerSortStr {
    String sortField();
}

接著用泛型包裝 Bo。包裝類實作先前的 BoSort 介面(或直接繼承 DefaultBoSortImp),在 getSortStr() 中透過反射讀取註解資訊:

public class RulerListDataWrapper<T> extends DefaultBoSortImp {
    private T data;

    public RulerListDataWrapper() { super(); }

    public RulerListDataWrapper(T data) {
        super();
        this.data = data;
    }

    public T getData() { return data; }
    public void setData(T data) { this.data = data; }

    /** 利用 T 的註解資訊實作此方法 */
    @Override
    public String getSortStr() {
        Class<?> temp = data.getClass();
        RulerSortStr anno = temp.getAnnotation(RulerSortStr.class);
        if (anno == null) {
            return "";
        }
        String sortField = anno.sortField();
        try {
            Field f = temp.getDeclaredField(sortField);
            f.setAccessible(true);
            return (String) f.get(data);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

這段程式有兩個要點。一是 setAccessible(true) 不可省略,否則讀取 private 欄位會丟 IllegalAccessException。二是所有反射操作都包在 try-catch 裡並回傳空字串——註解寫錯欄位名不該讓整個列表崩潰,降級成「無分組」是更合理的行為。

RulerUtil 泛型化

工具類同樣改寫成泛型,負責把 List<T> 轉換成 List<RulerListDataWrapper<T>>。標籤物件也是包裝器型別,泛型化之後,整個工具類不再依賴任何具體 Bo。

public class RulerUtil<T> {

    /** 列表索引 */
    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 List<RulerListDataWrapper<T>> genSortedDataAndTagLocation(
            List<T> myData, HashMap<String, Integer> tagLocation)
            throws InstantiationException, IllegalAccessException {

        List<RulerListDataWrapper<T>> res = getList(myData);

        // 先排序
        Collections.sort(res, new Comparator<RulerListDataWrapper<T>>() {
            @Override
            public int compare(RulerListDataWrapper<T> lhs, RulerListDataWrapper<T> 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++) {
            RulerListDataWrapper<T> temp = res.get(i);
            char tempTag = checkAndGetPinyin(temp);
            if (Arrays.binarySearch(letters, tempTag) < 0) {
                tempTag = '#';
            }
            if (nowTag != tempTag) {
                RulerListDataWrapper<T> tagBO = new RulerListDataWrapper<T>();
                tagBO.setTag(tempTag + "");
                res.add(i, tagBO);
                tagLocation.put(tempTag + "", i);
                i++;
                size++;
                nowTag = tempTag;
            }
        }
        tagLocation.put("#", 0);
        return res;
    }

    private 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';
    }

    public List<RulerListDataWrapper<T>> getList(List<T> data) {
        List<RulerListDataWrapper<T>> res = new ArrayList<RulerListDataWrapper<T>>();
        for (T t : data) {
            res.add(new RulerListDataWrapper<T>(t));
        }
        return res;
    }
}

插入標籤的迴圈有個細節值得注意:插入一筆標籤之後同時 i++ 與 size++。前者跳過剛插入的標籤本身,後者補上列表變長的部分,兩者缺一不可,否則會漏字或跳過資料項。而 tagLocation 記錄每個字母對應的索引位置,正是字母索引側邊欄跳轉所需的依據。

Adapter 泛型化

Adapter 消費的資料型別變成 List<RulerListDataWrapper<T>>:

public class RulerAdapter<T> extends BaseAdapter {

    /** 經過處理的資料 */
    private List<RulerListDataWrapper<T>> list;
    private Context mContext;

    public RulerAdapter(List<RulerListDataWrapper<T>> list, Context mContext) {
        this.list = list;
        this.mContext = mContext;
    }

    @Override public int getCount() { return list.size(); }

    @Override public RulerListDataWrapper<T> getItem(int position) {
        return list.get(position);
    }

    @Override public long getItemId(int position) { return 0; }

    /** 需要的時候覆寫此方法,提供自訂的非標籤視圖 */
    public View getContentView(int position, RulerListDataWrapper<T> bo) {
        return null;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext)
                    .inflate(R.layout.g_ruler_list_item, null);
            holder = new ViewHolder();
            holder.tag = (TextView) convertView.findViewById(R.id.g_ruler_list_item_tag);
            holder.content = (LinearLayout) convertView.findViewById(R.id.g_ruler_list_item);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final RulerListDataWrapper<T> bo = getItem(position);
        String tag = bo.getTag();

        if (tag != null) {              // 是標籤列
            holder.tag.setVisibility(View.VISIBLE);
            holder.content.setVisibility(View.GONE);
            holder.tag.setText(tag);
        } else {                        // 是內容列
            holder.content.removeAllViews();
            holder.tag.setVisibility(View.GONE);
            holder.content.setVisibility(View.VISIBLE);

            // 先取自訂視圖,若沒有則預設造一個 TextView
            View contentView = getContentView(position, bo);
            if (contentView == null) {
                TextView textV = new TextView(mContext);
                textV.setText(bo.getSortStr());
                textV.setTextColor(Color.BLACK);
                textV.setGravity(Gravity.CENTER_VERTICAL);
                textV.setTextSize(16);
                contentView = textV;
            }
            holder.content.addView(contentView,
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        }
        return convertView;
    }

    static class ViewHolder {
        TextView tag;
        LinearLayout content;
    }
}

這裡同時示範了兩個標準優化:用 ViewHolder 模式搭配 convertView.setTag() 避免重複 findViewById;用 getContentView() 回傳 null 作為擴充點,讓使用者只在需要時覆寫,不需要時維持預設外觀。標籤列與內容列共用一個 item 布局,靠可見性切換,也是常見做法。

Activity 泛型化

Activity 也一併泛型化,重點是對 RulerUtil 的呼叫與資料型別:

public abstract class RulerActivity<T> extends Activity {

    protected TextView noDataView;
    protected TextView RulerTag;
    protected ProgressBarWithText progress;
    protected ListView listView;
    protected RulerWidget ruler;

    private RulerAdapter<T> rulerAdapter;
    private List<T> originalList;
    private List<RulerListDataWrapper<T>> 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();
    }

    /** 子類別必須實作這個取資料的方法 */
    public abstract List<T> getDataList();

    /** 取得觸摸字母時列表要捲動到的位置;找不到則向前尋找 */
    private Integer getPosition(final int j) { . . . }

    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 = new RulerUtil<T>()
                        .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();
        }
    }
}

資料處理放在 AsyncTask 的 doInBackground 而非主執行緒,是因為排序時要跑漢字轉拼音,資料量大時相當耗時。失敗時把三個容器逐一清理並置 null,讓 onPostExecute 能用 dealedList == null 單一條件判斷失敗,這個設計比用旗標乾淨。

測試:使用端有多簡單

使用方要做的只有兩件事:繼承 RulerActivity,並在 Bo 上掛註解。

Bo:

@RulerSortStr(sortField = "testtr")
public class TestAnnotationBo {
    private String testtr;
    private String test2;

    public TestAnnotationBo() { super(); }

    public TestAnnotationBo(String testtr, String test2) {
        super();
        this.testtr = testtr;
        this.test2 = test2;
    }

    public String getTesttr() { return testtr; }
    public void setTesttr(String testtr) { this.testtr = testtr; }
    public String getTest2() { return test2; }
    public void setTest2(String test2) { this.test2 = test2; }
}

@RulerSortStr(sortField="testtr") 宣告了「用 testtr 欄位分組索引」。注意這個 Bo 沒有實作任何介面、沒有繼承任何抽象類,完全保持原樣。

Activity:

public class TestRulerAnnoActivity extends RulerActivity<TestAnnotationBo> {

    @Override
    public List<TestAnnotationBo> getDataList() {
        List<TestAnnotationBo> res = new ArrayList<TestAnnotationBo>();
        res.add(new TestAnnotationBo("爸爸", "sdds"));
        res.add(new TestAnnotationBo("aa", "sdds"));
        res.add(new TestAnnotationBo("阿姨", "sdds"));
        res.add(new TestAnnotationBo("bb", "sdds"));
        return res;
    }
}

只實作一個取資料的方法,排序、分組、插入標籤、字母索引定位全部自動完成。

重構到此結束。相較於上一版要求 Bo 實作介面,這一版把耦合點從「Bo 必須知道框架」轉變成「Bo 只需被標記」,這正是註解最適合承擔的角色——宣告意圖,而不承載行為。

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