Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 論字母導航的重要性,我們來實現一個聯系人字母導航列表吧!

論字母導航的重要性,我們來實現一個聯系人字母導航列表吧!

編輯:關於Android編程

說起這個字母導航,我相信大家都不陌生,不論是聯系人列表還是城市列表,基本上都是需要字母導航,那我們就有必要來研究一下這個思路的探索了,畢竟這是一個非常常用的功能,如果現在把輪子造好,那以後也可以節省很多的時間,同時,我們把思路理清楚了,對我們以後的幫助也是很大的,那好,既然如此,我們就一起來探索一下吧!

這裡寫圖片描述

我們首選新建一個項目——LettersNavigation

這裡寫圖片描述

OK,工程建立好之後我們來思考一下這個功能的一個實現邏輯<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjwvYmxvY2txdW90ZT4NCjxwPjxpbWcgYWx0PQ=="這裡寫圖片描述" src="/uploadfile/Collfiles/20160912/20160912092652210.png" title="\" />

邏輯不是很難,那我們首先要去做的就是把大致的框架搭好,也就是布局,我們來看

activity_main.xml




    
    

        

        

        
    

    
    <framelayout android:layout_height="match_parent" android:layout_width="match_parent">

        

        
        

        
        

    </framelayout>


這裡就比較好理解了,首選是最上面的一個搜索框,我們監聽裡面的內容,有內容的haunted我就顯示清除按鈕,下面是一個FrameLayout,他包裹著一個ListView顯示聯系人,一個TextView是作為字母提示的,最右邊就是我們的自定義字母導航欄LettersView了,同樣的,因為主頁有輸入框,他只要一進去就會獲取到焦點彈起輸入法,這樣的交互式不友好的,我們在清單文件中的Activity根節點加一個屬性

 android:windowSoftInputMode="adjustUnspecified|stateHidden"

還有我們搜索的輸入框的背景,因為我沒有找到合適的.9圖片,PS也不是很懂,就自己繪制了一個圓角的背景

search_bg.xml



    
    

同理,還有我們字母提示TextView的背景

toast_bg.xml



    
    

在我看來,xml繪制動畫也好,顯示效果也好,都是十分的方便的,這個一定要掌握以下哦!,好的,前期的架子搭完了,我們現在可以重點來看一下這個字母View了,其實他就兩個步驟,在我看來,首先繪制這個View,然後通過手勢監聽去逐幀他的選中字母,拿這樣的話,我們的繪制應該是這個樣子的:

    /**
     * 繪制
     *
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /**
         * 為了排列26個字母,我們可以用坐標點來計算,X居中,Y為 1/27 的遞加計算
         * 首先獲取到我們View的寬高
         */
        int viewWidth = getWidth();
        int viewHeight = getHeight();
        //計算一個字母的高度
        int singleHeight = viewHeight / strChars.length;
        //循環繪制字母
        for (int i = 0; i < strChars.length; i++) {
            //設置選中字母的顏色
            if (i == checkIndex) {
                mPaint.setColor(Color.BLACK);
                mPaint.setTextSize(50);
            } else {
                mPaint.setColor(Color.WHITE);
                //設置字體大小
                mPaint.setTextSize(40);
            }
            /**
             * 繪制字母
             * x: (view的寬度 - 文本的寬度)/ 2
             * y:  singleHeight * x + singleHeight  //單個字母的高度 + 最上面的字幕空白高度
             */
            float lettersX = (viewWidth - mPaint.measureText(strChars[i])) / 2;
            float lettersY = singleHeight * i + singleHeight;
            //繪制
            canvas.drawText(strChars[i], lettersX, lettersY, mPaint);
            //重繪
            mPaint.reset();
        }
    }

然後我們就可以來預覽以下效果了

這裡寫圖片描述

感覺還是有點挫呀,不過先不管,我們仔細看下這個onDraw方法,其實我們主要還是計算x,y的坐標然後去繪制,在繪制的時候我們定義一個選中的下標,,默認為0,所以默認選中A,好的,那我們再來實現手勢的監聽吧!這裡我們用事件分發來做是最合適的了

    /**
     * 事件分發
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //判斷手勢
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                setBackgroundResource(R.color.colorAccent);
                //獲取點擊的Y坐標,以此來判斷選中的字母
                float y = event.getY();
                Log.i(TAG, "y:" + y);
                //第一次被選中的下標
                int oldCheckIndex = checkIndex;
                /**
                 * 計算選中的字母
                 * strChars[當前Y / View的高度 * 字母個數]
                 */
                int c = (int) (y / getHeight() * strChars.length);
                Log.i(TAG, "c:" + c);
                //判斷移動
                if (oldCheckIndex != c) {
                    //不能越界
                    if (c >= 0 && c < strChars.length) {
                        if (mTextView != null) {
                            mTextView.setVisibility(View.VISIBLE);
                            mTextView.setText(strChars[c]);
                        }
                    }
                    checkIndex = c;
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                //設置透明背景
                setBackgroundResource(android.R.color.transparent);
                //恢復不選中
                checkIndex = -1;
                invalidate();
                //是否顯示
                if (mTextView != null) {
                    mTextView.setVisibility(View.INVISIBLE);
                }
                break;
        }
        return true;
    }

其實這裡也是比較簡單的,不過這裡有一個set/get的TextView,需要在MainActivity裡面去設置一下

 mLettersView = (LettersView) findViewById(R.id.mLettersView);
 mLettersView.setmTextView(tvToast);

這樣我們就可以看到實際的效果了

這裡寫圖片描述

這個View當然不止做這麼一點點事情了,我們等下還需要他與ListView去聯動呢,那既然如此,我們先把ListView給撸出來,這個ListView其實很簡單,不要看我們的不規則排列,其實他的原理就是item上有兩個TextView,上面是字母,下面是姓名,當然,我們要去轉換判斷一下並且計算出誰該顯示字母,誰有需要去隱藏,所以我們的item應該是

list_item.xml




    

    

然後就是我們的實體類了

LettersModel

package com.liuguilin.lettersnavigation.entity;

/*
 *  項目名:  LettersNavigation 
 *  包名:    com.liuguilin.lettersnavigation.entity
 *  文件名:   LettersModel
 *  創建者:   LGL
 *  創建時間:  2016/9/11 16:55
 *  描述:    聯系人實體
 */

public class LettersModel {

    //字母
    private String letter;
    //聯系人
    private String name;

    public String getLetter() {
        return letter;
    }

    public void setLetter(String letter) {
        this.letter = letter;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

當然,我們又兩個重要的環節,一個是數據,還有一個適配器,我們先來看下數據怎麼去用,首先我們模擬一些數據

//聯系人數據模擬
private String[] strName = {"張三", "李四", "李七", "劉某人", "王五", "Android", "IOS", "王寡婦","阿三", "爸爸", "媽媽", "CoCo", "弟弟", "爾康", "紫薇", "小燕子", "皇阿瑪", "福爾康", "哥哥", "Hi", "I", "傑克", "克星", "樂樂", "你好", "Oppo", "皮特", "曲奇餅","日啊", "思思", "缇娜", "U", "V", "王大叔", "嘻嘻", "一小伙子", "撒貝寧", "吱吱", "舅舅", "老總", "隔壁老王", "許仙"};

然後我們寫個方法

    /**
     * 聯系人數組轉換實體數據
     *
     * @return
     */
    private List parsingData() {
        List listModel = new ArrayList<>();
        Log.i(TAG, " strName.length:" + strName.length);
        for (int i = 0; i < strName.length; i++) {
            LettersModel model = new LettersModel();
            model.setName(strName[i]);
            Log.i(TAG, strName[i]);
            //轉換拼音截取首字母並且大寫
            String pinyin = Trans2PinYin.trans2PinYin(strName[i]);
            Log.i(TAG, "pinyin:" + pinyin);
            String letter = pinyin.substring(0, 1).toUpperCase();
            Log.i(TAG, "letter:" + letter);
            model.setLetter(letter);
            listModel.add(model);
        }
        return listModel;
    }

這個方法主要是把數據填充到我們的數據集裡面,然後我們就要進行排序了,我們排序的規則是A-Z #,那我們就得自定義一個排序規則

LettersSorting

package com.liuguilin.lettersnavigation.utils;

/*
 *  項目名:  LettersNavigation 
 *  包名:    com.liuguilin.lettersnavigation.utils
 *  文件名:   LettersSorting
 *  創建者:   LGL
 *  創建時間:  2016/9/11 18:04
 *  描述:    字母排序算法
 */

import com.liuguilin.lettersnavigation.entity.LettersModel;

import java.util.Comparator;

public class LettersSorting implements Comparator {

    @Override
    public int compare(LettersModel lettersModel, LettersModel t1) {
        //給我兩個對象,我只比較他的字母
        return lettersModel.getLetter().compareTo(t1.getLetter());
    }
}

這樣我們就可以調通了,我把MainActivity的代碼全部貼上你就能看的十分的清晰了

MainActivity

package com.liuguilin.lettersnavigation;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.liuguilin.lettersnavigation.adapter.LettersAdapter;
import com.liuguilin.lettersnavigation.entity.LettersModel;
import com.liuguilin.lettersnavigation.utils.LettersSorting;
import com.liuguilin.lettersnavigation.utils.Trans2PinYin;
import com.liuguilin.lettersnavigation.view.LettersView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //TAG
    private static final String TAG = "Letters";

    //聯系人列表
    private ListView mListView;
    //字母提示
    private TextView tvToast;
    //字母列表
    private LettersView mLettersView;
    //搜索框
    private EditText et_search;
    //列表數據
    private List mList = new ArrayList<>();
    //數據源
    private LettersAdapter adapter;
    //聯系人數據模擬
    private String[] strName = {"張三", "李四", "李七", "劉某人", "王五", "Android", "IOS", "王寡婦","阿三", "爸爸", "媽媽", "CoCo", "弟弟", "爾康", "紫薇", "小燕子", "皇阿瑪", "福爾康", "哥哥", "Hi", "I", "傑克", "克星", "樂樂", "你好", "Oppo", "皮特", "曲奇餅","日啊", "思思", "缇娜", "U", "V", "王大叔", "嘻嘻", "一小伙子", "撒貝寧", "吱吱", "舅舅", "老總", "隔壁老王", "許仙"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    /**
     * 初始化View
     */
    private void initView() {
        mListView = (ListView) findViewById(R.id.mListView);
        tvToast = (TextView) findViewById(R.id.tvToast);
        et_search = (EditText) findViewById(R.id.et_search);
        mLettersView = (LettersView) findViewById(R.id.mLettersView);
        mLettersView.setmTextView(tvToast);

        //加載聯系人的模擬數據
        mList = parsingData();
        //對字母進行排序A-Z #
        Collections.sort(mList, new LettersSorting());
        //加載適配器
        adapter = new LettersAdapter(this, mList);
        //設置數據
        mListView.setAdapter(adapter);
    }

    /**
     * 聯系人數組轉換實體數據
     *
     * @return
     */
    private List parsingData() {
        List listModel = new ArrayList<>();
        Log.i(TAG, " strName.length:" + strName.length);
        for (int i = 0; i < strName.length; i++) {
            LettersModel model = new LettersModel();
            model.setName(strName[i]);
            Log.i(TAG, strName[i]);
            //轉換拼音截取首字母並且大寫
            String pinyin = Trans2PinYin.trans2PinYin(strName[i]);
            Log.i(TAG, "pinyin:" + pinyin);
            String letter = pinyin.substring(0, 1).toUpperCase();
            Log.i(TAG, "letter:" + letter);
            model.setLetter(letter);
            listModel.add(model);
        }
        return listModel;
    }
}

OK,正如你所見,我們最重要的是LettersAdapter,我們先來分析一下這個adapter,其實他要做的就兩件事情,首選把字母的第一個排出來,然後依次顯示數據,我們直接看代碼

LettersAdapter

package com.liuguilin.lettersnavigation.adapter;

/*
 *  項目名:  LettersNavigation 
 *  包名:    com.liuguilin.lettersnavigation.adapter
 *  文件名:   LettersAdapter
 *  創建者:   LGL
 *  創建時間:  2016/9/11 18:12
 *  描述:    聯系人適配器
 */

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.liuguilin.lettersnavigation.R;
import com.liuguilin.lettersnavigation.entity.LettersModel;

import java.util.List;

public class LettersAdapter extends BaseAdapter {

    //上下文
    private Context mContext;
    //數據集
    private List mList;
    //布局加載器
    private LayoutInflater mInflater;
    //實體類
    private LettersModel model;

    public LettersAdapter(Context mContext, List mList) {
        this.mContext = mContext;
        this.mList = mList;

        //獲取系統服務
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    @Override
    public Object getItem(int i) {
        return mList.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder vHolder = null;
        if (view == null) {
            vHolder = new ViewHolder();
            //加載布局
            view = mInflater.inflate(R.layout.list_item, null);
            vHolder.tvLetters = (TextView) view.findViewById(R.id.tvLetters);
            vHolder.tvName = (TextView) view.findViewById(R.id.tvName);
            view.setTag(vHolder);
        } else {
            vHolder = (ViewHolder) view.getTag();
        }
        //選中下標
        model = mList.get(i);
        //獲取首字母顯示人
        int firstPosition = getNmaeForPosition(i);
        //第一個
        int index = getPositionForNmae(firstPosition);
        //需要顯示字母
        if (index == i) {
            vHolder.tvLetters.setVisibility(View.VISIBLE);
            vHolder.tvLetters.setText(model.getLetter());
        } else {
            vHolder.tvLetters.setVisibility(View.GONE);
        }
        vHolder.tvName.setText(model.getName());
        return view;
    }

    /**
     * 緩存優化
     */
    class ViewHolder {
        private TextView tvLetters;
        private TextView tvName;
    }

    /**
     * 通過首字母獲取該首字母要顯示的第一個人的下標
     *
     * @param position
     * @return
     */
    private int getPositionForNmae(int position) {
        for (int i = 0; i < getCount(); i++) {
            String letter = mList.get(i).getLetter();
            //首字母顯示
            char firstChar = letter.toUpperCase().charAt(0);
            if (firstChar == position) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 根據名稱拿到下標
     *
     * @param position
     * @return
     */
    private int getNmaeForPosition(int position) {
        return mList.get(position).getLetter().charAt(0);
    }

}

這裡最關鍵的也就在於getPositionForNmae方法他直接計算出了我們一堆同類型的聯系人中的第一個數據並且返回出來,然後我們再利用getNmaeForPosition拿到需要顯示的position,OK,到這裡,我們基本上就可以看到很大一部分效果了

這裡寫圖片描述

現在這個大體的架構就已經搭建出來了,我們現在最後的難點就是如何字母導航和ListView的聯動了,我們只能回到我們的LettersView,其實這個說難也不難,主要還是一個思想,我們可以用接口的形式去做,首先我們定義一個接口

  /**
     * 接口回調/ListView聯動
     */
    public interface OnLettersListViewListener {
        public void onLettersListener(String s);
    }

並且實現它的set/get方法,然後我們在選中的手勢事件中,我們去直接設置

 //效果聯動
 if (onLettersListViewListener != null) {
      onLettersListViewListener.onLettersListener(strChars[c]);
 }

這裡我們回傳回去的是我們選中的字母,我們再回到我們的MainActivity,然後直接

implements LettersView.OnLettersListViewListener

設置了我們的監聽之後,我們可以直接移動

    /**
     * ListView與字母導航聯動
     *
     * @param s
     */
    @Override
    public void onLettersListener(String s) {
        //對應的位置
        int position = adapter.getPositionForNmae(s.charAt(0));
        //移動
        mListView.setSelection(position);
    }

我們可以來看一下最終的效果

這裡寫圖片描述

現在思路是不是一場的清晰?這裡我把這個View的代碼貼上

LettersView

package com.liuguilin.lettersnavigation.view;

/*
 *  項目名:  LettersNavigation 
 *  包名:    com.liuguilin.lettersnavigation.view
 *  文件名:   LettersView
 *  創建者:   LGL
 *  創建時間:  2016/9/11 11:58
 *  描述:    字母導航
 */

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.liuguilin.lettersnavigation.R;

public class LettersView extends View {

    //TAG
    private static final String TAG = "LettersView";

    //字母數組,#代表未知,比如數字開頭
    private String[] strChars = {"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", "#"};
    //畫筆
    private Paint mPaint;
    //選中字母的下標
    private int checkIndex;
    //字母提示的TextView,需要set/get動態設置顯示內容
    private TextView mTextView;
    //接口回調
    private OnLettersListViewListener onLettersListViewListener;

    public LettersView(Context context) {
        super(context);
        init();
    }

    public LettersView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LettersView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        //實例化畫筆
        mPaint = new Paint();
        //設置style
        mPaint.setTypeface(Typeface.DEFAULT_BOLD);
        //設置抗鋸齒
        mPaint.setAntiAlias(true);
    }

    /**
     * 繪制
     *
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /**
         * 為了排列26個字母,我們可以用坐標點來計算,X居中,Y為 1/27 的遞加計算
         * 首先獲取到我們View的寬高
         */
        int viewWidth = getWidth();
        int viewHeight = getHeight();
        //計算一個字母的高度
        int singleHeight = viewHeight / strChars.length;
        //循環繪制字母
        for (int i = 0; i < strChars.length; i++) {
            //設置選中字母的顏色
            if (i == checkIndex) {
                mPaint.setColor(Color.WHITE);
                mPaint.setTextSize(50);
            } else {
                mPaint.setColor(Color.BLACK);
                //設置字體大小
                mPaint.setTextSize(40);
            }
            /**
             * 繪制字母
             * x: (view的寬度 - 文本的寬度)/ 2
             * y:  singleHeight * x + singleHeight  //單個字母的高度 + 最上面的字幕空白高度
             */
            float lettersX = (viewWidth - mPaint.measureText(strChars[i])) / 2;
            float lettersY = singleHeight * i + singleHeight;
            //繪制
            canvas.drawText(strChars[i], lettersX, lettersY, mPaint);
            //重繪
            mPaint.reset();
        }
    }

    public TextView getmTextView() {
        return mTextView;
    }

    public void setmTextView(TextView mTextView) {
        this.mTextView = mTextView;
    }

    /**
     * 事件分發
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //判斷手勢
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                setBackgroundResource(R.color.colorAccent);
                //獲取點擊的Y坐標,以此來判斷選中的字母
                float y = event.getY();
                Log.i(TAG, "y:" + y);
                //第一次被選中的下標
                int oldCheckIndex = checkIndex;
                /**
                 * 計算選中的字母
                 * strChars[當前Y / View的高度 * 字母個數]
                 */
                int c = (int) (y / getHeight() * strChars.length);
                Log.i(TAG, "c:" + c);
                //判斷移動
                if (oldCheckIndex != c) {
                    //不能越界
                    if (c >= 0 && c < strChars.length) {
                        //效果聯動
                        if (onLettersListViewListener != null) {
                            onLettersListViewListener.onLettersListener(strChars[c]);
                        }
                        if (mTextView != null) {
                            mTextView.setVisibility(View.VISIBLE);
                            mTextView.setText(strChars[c]);
                        }
                    }
                    checkIndex = c;
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                //設置透明背景
                setBackgroundResource(android.R.color.transparent);
                //恢復不選中
                checkIndex = -1;
                invalidate();
                //是否顯示
                if (mTextView != null) {
                    mTextView.setVisibility(View.INVISIBLE);
                }
                break;
        }
        return true;
    }

    public OnLettersListViewListener getOnLettersListViewListener() {
        return onLettersListViewListener;
    }

    public void setOnLettersListViewListener(OnLettersListViewListener onLettersListViewListener) {
        this.onLettersListViewListener = onLettersListViewListener;
    }

    /**
     * 接口回調/ListView聯動
     */
    public interface OnLettersListViewListener {
        public void onLettersListener(String s);
    }
}

ok,這裡最終小伙伴是不是還有一個疑問,就是我們使用到的Trans2PinYin這個類是什麼?事實上,這個類的唯一功能就是把漢子轉化成拼音的工具類,在android官方的通訊錄中就有這個類,有興趣的可以去看一下源碼,最後我把這個類的源碼貼上:

Trans2PinYin

package com.liuguilin.lettersnavigation.utils;

/*
 *  項目名:  HanZiToPinYinSample 
 *  包名:    com.liuguilin.hanzitopinyinsample
 *  文件名:   Trans2PinYin
 *  創建者:   LGL
 *  創建時間:  2016/8/23 17:05
 *  描述:    漢字轉拼音
 */

public class Trans2PinYin {

    private static int[] pyvalue = new int[]{-20319, -20317, -20304, -20295,
            -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036,
            -20032, -20026, -20002, -19990, -19986, -19982, -19976, -19805,
            -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741,
            -19739, -19728, -19725, -19715, -19540, -19531, -19525, -19515,
            -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275,
            -19270, -19263, -19261, -19249, -19243, -19242, -19238, -19235,
            -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006,
            -19003, -18996, -18977, -18961, -18952, -18783, -18774, -18773,
            -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697,
            -18696, -18526, -18518, -18501, -18490, -18478, -18463, -18448,
            -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201,
            -18184, -18183, -18181, -18012, -17997, -17988, -17970, -17964,
            -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752,
            -17733, -17730, -17721, -17703, -17701, -17697, -17692, -17683,
            -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427,
            -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,
            -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470,
            -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423,
            -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216,
            -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158,
            -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903,
            -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659,
            -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435,
            -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369,
            -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150,
            -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121,
            -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930,
            -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902,
            -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674,
            -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429,
            -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345,
            -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135,
            -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,
            -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907,
            -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847,
            -13831, -13658, -13611, -13601, -13406, -13404, -13400, -13398,
            -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343,
            -13340, -13329, -13326, -13318, -13147, -13138, -13120, -13107,
            -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888,
            -12875, -12871, -12860, -12858, -12852, -12849, -12838, -12831,
            -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556,
            -12359, -12346, -12320, -12300, -12120, -12099, -12089, -12074,
            -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798,
            -11781, -11604, -11589, -11536, -11358, -11340, -11339, -11324,
            -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041,
            -11038, -11024, -11020, -11019, -11018, -11014, -10838, -10832,
            -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533,
            -10519, -10331, -10329, -10328, -10322, -10315, -10309, -10307,
            -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};
    private static String[] pystr = new String[]{"a", "ai", "an", "ang",
            "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng",
            "bi", "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca",
            "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan",
            "chang", "chao", "che", "chen", "cheng", "chi", "chong", "chou",
            "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci",
            "cong", "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai",
            "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die",
            "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo",
            "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo",
            "fou", "fu", "ga", "gai", "gan", "gang", "gao", "ge", "gei", "gen",
            "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui",
            "gun", "guo", "ha", "hai", "han", "hang", "hao", "he", "hei",
            "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang",
            "hui", "hun", "huo", "ji", "jia", "jian", "jiang", "jiao", "jie",
            "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka",
            "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou",
            "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la",
            "lai", "lan", "lang", "lao", "le", "lei", "leng", "li", "lia",
            "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long",
            "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man",
            "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao",
            "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan",
            "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang",
            "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",
            "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei",
            "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po",
            "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing",
            "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao",
            "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui",
            "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen",
            "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen",
            "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang",
            "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui",
            "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng",
            "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan",
            "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen",
            "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie",
            "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya",
            "yan", "yang", "yao", "ye", "yi", "yin", "ying", "yo", "yong",
            "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang",
            "zao", "ze", "zei", "zen", "zeng", "zha", "zhai", "zhan", "zhang",
            "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu",
            "zhua", "zhuai", "zhuan", "zhuang", "zhui", "zhun", "zhuo", "zi",
            "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"};
    private StringBuilder buffer;
    private String resource;
    private static Trans2PinYin chineseSpelling = new Trans2PinYin();

    public static Trans2PinYin getInstance() {
        return chineseSpelling;
    }

    public String getResource() {
        return resource;
    }

    public void setResource(String resource) {
        this.resource = resource;
    }

    private int getChsAscii(String chs) {
        int asc = 0;
        try {
            byte[] bytes = chs.getBytes("gb2312");
            if (bytes == null || bytes.length > 2 || bytes.length <= 0) { // 錯誤
                // log
                throw new RuntimeException("illegal resource string");
                // System.out.println("error");
            }
            if (bytes.length == 1) { // 英文字符
                asc = bytes[0];
            }
            if (bytes.length == 2) { // 中文字符
                int hightByte = 256 + bytes[0];
                int lowByte = 256 + bytes[1];
                asc = (256 * hightByte + lowByte) - 256 * 256;
            }
        } catch (Exception e) {
            System.out
                    .println("ERROR:ChineseSpelling.class-getChsAscii(String chs)"
                            + e);
            // e.printStackTrace();
        }
        return asc;
    }

    /**
     * 轉換單個漢字
     *
     * @param str
     * @return
     */
    public String convert(String str) {
        String result = null;
        int ascii = getChsAscii(str);
        if (ascii > 0 && ascii < 160) {
            result = String.valueOf((char) ascii);
        } else {
            for (int i = (pyvalue.length - 1); i >= 0; i--) {
                if (pyvalue[i] <= ascii) {
                    result = pystr[i];
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 轉換一個或多個漢字
     *
     * @param str
     * @return
     */
    public String convertAll(String str) {
        String result = "";
        String strTemp = null;
        for (int j = 0; j < str.length(); j++) {
            strTemp = str.substring(j, j + 1);
            int ascii = getChsAscii(strTemp);
            if (ascii > 0 && ascii < 160) {
                result += String.valueOf((char) ascii);
            } else {
                for (int i = (pyvalue.length - 1); i >= 0; i--) {
                    if (pyvalue[i] <= ascii) {
                        result += pystr[i];
                        break;
                    }
                }
            }
        }
        return result;
    }

    public String getSelling(String chs) {
        String key, value;
        buffer = new StringBuilder();
        for (int i = 0; i < chs.length(); i++) {
            key = chs.substring(i, i + 1);
            if (key.getBytes().length == 2) {
                value = (String) convert(key);
                if (value == null) {
                    value = "unknown";
                }
            } else {
                value = key;
            }
            buffer.append(value);
        }
        return buffer.toString();
    }

    public String getSpelling() {
        return this.getSelling(this.getResource());
    }

    /**
     * 轉換為拼音
     *
     * @param str
     * @return
     */
    public static String trans2PinYin(String str) {
        return Trans2PinYin.getInstance().convertAll(str);
    }

}

最後的一些細節,比如Edittext監聽什麼的

 et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    tv_cancel.setVisibility(View.VISIBLE);
                } else {
                    tv_cancel.setVisibility(View.GONE);
                }
            }
        });

這些小細節大家等下自行下載我上傳的源碼看吧!

最後,這篇博客到這裡也就結束了,字母導航的思路也借鑒了很多前人,自己摸索了一天多才摸索出來,感覺這個擴展性還可以強一點,無奈精力有限,篇幅也有限了,等我下次再繼續研究,這麼多,能看到這裡也是不容易,我寫的也不容易,給我點個贊吧!!!

我們最後看一下最終的效果

這裡寫圖片描述

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved