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

自定義 View 實作:仿通訊錄側邊索引欄,實現 A–Z 字母快速定位

編輯:關於 Android 程式設計

手機通訊錄大概都有這樣的效果:

這個互動幾乎成了 Android 通訊錄的標準配備。今天我們就來看看它是怎麼做出來的。

一、整體規劃

1. 頁面功能拆解

整個畫面可以拆成兩半:左邊是一個 ListView,右邊是一個自定義 View。左邊 ListView 的特殊之處在於我對聯繫人做了分組顯示,常見的實現思路有兩種:

  • 使用 ExpandableListView 來承載分組結構。
  • 使用普通 ListView,在 Adapter 中實作 SectionIndexer 接口,自行處理索引邏輯。

兩種都不算難,屬於普通控件的組合運用。本文採用第二種,第一種可以自行研究。

右邊那個豎排字母條就是今天的主角——一個自定義 View,A、B……# 這些字符全部透過 canvas.drawText() 繪製,再重寫 onTouchEvent() 來處理觸摸。

2. 預期效果

  • 左邊 ListView 按分組顯示聯繫人。
  • 滑動左邊 ListView 時,右邊索引條中高亮的字母會同步變化。
  • 手指在右邊索引條上滑動時,滑過的字母變色,同時頁面正中間彈出一個 TextView 顯示當前字母。
  • 手指按下時索引條背景變灰,鬆開後恢復透明。

二、左側分組 ListView

1. 資料模型

先為資料集建立一個實體類:

public class User {
    private int img;
    private String username;
    private String pinyin;
    private String firstLetter;

    public User() { }

    public User(String firstLetter, int img, String pinyin, String username) {
        this.firstLetter = firstLetter;
        this.img = img;
        this.pinyin = pinyin;
        this.username = username;
    }

    // getter / setter 省略
}

username 存用戶名,img 是頭像資源 id,pinyin 是姓名拼音,firstLetter 是拼音首字母。

2. 初始化資料並排序

private void initData() {
    list = new ArrayList<>();
    String[] allUserNames = getResources().getStringArray(R.array.arrUsernames);

    for (String allUserName : allUserNames) {
        User user = new User();
        user.setUsername(allUserName);

        String convert = ChineseToPinyinHelper.getInstance()
                .getPinyin(allUserName).toUpperCase();
        user.setPinyin(convert);

        String substring = convert.substring(0, 1);
        if (substring.matches("[A-Z]")) {
            user.setFirstLetter(substring);
        } else {
            // 非漢字開頭的姓名統一歸到 # 分組
            user.setFirstLetter("#");
        }
        list.add(user);
    }

    Collections.sort(list, new Comparator<User>() {
        @Override
        public int compare(User lhs, User rhs) {
            if (lhs.getFirstLetter().contains("#")) {
                return 1;
            } else if (rhs.getFirstLetter().contains("#")) {
                return -1;
            } else {
                return lhs.getFirstLetter().compareTo(rhs.getFirstLetter());
            }
        }
    });
}

透過 ChineseToPinyinHelper 把中文轉成拼音,取首字母;若首字母落在 A–Z 之外(例如以數字或符號開頭),就統一歸入 # 分組,並排到最後。排序本身是純 Java 操作。

3. 實作 SectionIndexer 的 Adapter

public class MyAdapter extends BaseAdapter implements SectionIndexer {

    private List<User> list;
    private Context context;
    private LayoutInflater inflater;

    public MyAdapter(Context context, List<User> list) {
        this.context = context;
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

    @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) {
            convertView = inflater.inflate(R.layout.listview_item, null);
            holder = new ViewHolder();
            holder.showLetter = (TextView) convertView.findViewById(R.id.show_letter);
            holder.username = (TextView) convertView.findViewById(R.id.username);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        User user = list.get(position);
        holder.username.setText(user.getUsername());

        // 當前 position 屬於哪個分組
        int sectionForPosition = getSectionForPosition(position);
        // 該分組第一項的 position
        int positionForSection = getPositionForSection(sectionForPosition);

        // 只有分組首項才顯示字母標頭
        if (position == positionForSection) {
            holder.showLetter.setVisibility(View.VISIBLE);
            holder.showLetter.setText(user.getFirstLetter());
        } else {
            holder.showLetter.setVisibility(View.GONE);
        }
        return convertView;
    }

    @Override
    public Object[] getSections() {
        return new Object[0];
    }

    /** 傳入分組值(A…Z 的字元碼),取得該分組第一項的 position */
    @Override
    public int getPositionForSection(int sectionIndex) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getFirstLetter().charAt(0) == sectionIndex) {
                return i;
            }
        }
        return -1;
    }

    /** 傳入 position,取得該項所屬分組的字元碼 */
    @Override
    public int getSectionForPosition(int position) {
        return list.get(position).getFirstLetter().charAt(0);
    }

    class ViewHolder {
        TextView username, showLetter;
    }
}

Adapter 大部分和傳統寫法一致,差別在實作了 SectionIndexer。其中真正用到的是後兩個方法:

  • getPositionForSection(int sectionIndex):傳入分組值(A…Z),回傳該分組第一個 item 的 position。
  • getSectionForPosition(int position):傳入一個 position,回傳該 item 所屬的分組值。

item 佈局中所有項目結構相同,都有一個顯示分組字母的 TextView,所以必須在 getView() 裡判斷:當前項若正好是所在分組的第一項,就顯示字母標頭,否則隱藏。這段判斷就是上面程式碼的最後幾行。

佈局寫好、Adapter 掛上之後,左邊就大功告成:

ListView listView = (ListView) findViewById(R.id.lv);
MyAdapter adapter = new MyAdapter(this, list);
listView.setAdapter(adapter);

三、右側索引欄 LetterIndexView

1. 成員變數

// 當前手指滑到的位置
private int choosedPosition = -1;
// 畫文字的畫筆
private Paint paint;
// 右邊的所有字符
private String[] letters = new String[]{"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", "#"};
// 頁面正中央的提示 TextView
private TextView textViewDialog;
// 回呼接口:讓手指滑動時 ListView 跟著滾動
private UpdateListView updateListView;

構造方法中只需要初始化畫筆:

public LetterIndexView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setTextSize(24);
}

2. 繪製字母

@Override
protected void onDraw(Canvas canvas) {
    int perTextHeight = getHeight() / letters.length;
    for (int i = 0; i < letters.length; i++) {
        if (i == choosedPosition) {
            paint.setColor(Color.RED);
        } else {
            paint.setColor(Color.BLACK);
        }
        canvas.drawText(letters[i],
                (getWidth() - paint.measureText(letters[i])) / 2,
                (i + 1) * perTextHeight, paint);
    }
}

先用總高度除以字符數,算出每個字符可分配的垂直空間;再用 paint.measureText() 讓文字水平居中。若某個位置正好是手指所在處,就畫成紅色。

3. 處理觸摸事件

@Override
public boolean onTouchEvent(MotionEvent event) {
    int perTextHeight = getHeight() / letters.length;
    float y = event.getY();
    int currentPosition = (int) (y / perTextHeight);
    String letter = letters[currentPosition];

    switch (event.getAction()) {
        case MotionEvent.ACTION_UP:
            setBackgroundColor(Color.TRANSPARENT);
            if (textViewDialog != null) {
                textViewDialog.setVisibility(View.GONE);
            }
            break;
        default:
            setBackgroundColor(Color.parseColor("#cccccc"));
            if (currentPosition > -1 && currentPosition < letters.length) {
                if (textViewDialog != null) {
                    textViewDialog.setVisibility(View.VISIBLE);
                    textViewDialog.setText(letter);
                }
                if (updateListView != null) {
                    updateListView.updateListView(letter);
                }
                choosedPosition = currentPosition;
            }
            break;
    }
    invalidate();
    return true;
}

事件處理可以分成兩類:手指抬起,以及其餘所有動作。要知道手指點在哪個字母上,只需把 Y 座標除以單字符高度得到 position,再從 letters 陣列取值。定位之後,改背景色、更新中間的提示文字、把 position 記到 choosedPosition,最後 invalidate() 重繪——因為 choosedPosition 已變,對應字母自然會變色。

4. 雙向同步

手指滑右邊時要帶動 ListView 滾動,用接口回呼即可:

public void updateLetterIndexView(int currentChar) {
    for (int i = 0; i < letters.length; i++) {
        if (currentChar == letters[i].charAt(0)) {
            choosedPosition = i;
            invalidate();
            break;
        }
    }
}

反過來,ListView 滾動時也要更新右邊的高亮,只需在自定義 View 中公開這個方法給外部呼叫。

5. Activity 中把兩邊接起來

TextView textView = (TextView) findViewById(R.id.show_letter_in_center);
final LetterIndexView letterIndexView =
        (LetterIndexView) findViewById(R.id.letter_index_view);
letterIndexView.setTextViewDialog(textView);

letterIndexView.setUpdateListView(new LetterIndexView.UpdateListView() {
    @Override
    public void updateListView(String currentChar) {
        int positionForSection = adapter.getPositionForSection(currentChar.charAt(0));
        listView.setSelection(positionForSection);
    }
});

listView.setOnScrollListener(new AbsListView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) { }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        int sectionForPosition = adapter.getSectionForPosition(firstVisibleItem);
        letterIndexView.updateLetterIndexView(sectionForPosition);
    }
});

整條鏈路就通了:右邊滑動 → 透過接口呼叫 setSelection() 讓列表跳位;左邊滾動 → 透過 onScroll() 回呼 updateLetterIndexView() 更新高亮。核心其實就是 SectionIndexer 提供的兩個「位置 ↔ 分組」換算方法,加上一個自定義 View 的座標計算。

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