1. 程式人生 > >Android實現首字母導航條(仿微信)

Android實現首字母導航條(仿微信)

本部落格介紹Android實現首字母導航條,先看張效果圖,具體怎麼實現看程式碼吧

這裡寫圖片描述

具體的步驟

1.整體佈局的顯示
2. 實現A-Z的分組
3. 自定義A-Z的導航條
4. 中間顯示/隱藏觸控到導航條具體的字母

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:orientation="vertical" tools:context="com.example.firstnavigation.MainActivity">
<FrameLayout android:layout_width="match_parent" android:layout_height
="wrap_content">
<!--ListView--> <ListView android:id="@+id/friend_listview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" /> <!--中間顯示的字母--> <TextView
android:id="@+id/tv_first" android:layout_width="80dp" android:layout_height="80dp" android:layout_gravity="center" android:text="A" android:textColor="#ff0000" android:textSize="30sp" android:visibility="gone" />
<!--自定義導航條--> <com.example.firstnavigation.SlidView android:id="@+id/slidView" android:layout_width="30dp" android:layout_height="match_parent" android:layout_gravity="right|center" /> </FrameLayout> </LinearLayout>

item.xml —-》ListView對應item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical">

    <!--首字母-->

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#9e9d9d"
        android:textColor="#fff"
        android:textSize="16sp" />

    <!--首字母對應的首個漢字-->

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#262626"
        android:textSize="16sp" />
</LinearLayout>

聯絡人Bean

public class Contact {
    //姓名
    private String name;
    //姓名的首字母
    private String firstWord;

    public String getName() {
        return name;
    }

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

    public String getFirstWord() {
        return firstWord;
    }

    public void setFirstWord(String ch) {
        this.firstWord = ch;
    }
}


ContactAdapter.java

public class ContactAdapter extends BaseAdapter {
    private ArrayList<Contact> arrayList;
    private Context context;
    private String pre = "A";

    public ContactAdapter(ArrayList<Contact> arrayList, Context context) {
        this.arrayList = arrayList;
        this.context = context;
    }

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

    @Override
    public Object getItem(int position) {
        return arrayList.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
            viewHolder.tv_firstWord = (TextView) convertView.findViewById(R.id.tv);
            viewHolder.name = (TextView) convertView.findViewById(R.id.name);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.tv_firstWord.setText(String.valueOf(arrayList.get(position).getFirstWord()));
        viewHolder.name.setText(arrayList.get(position).getName());
        /**
         * 分組:根據漢字的首字母
         */
        viewHolder.tv_firstWord.setVisibility(!arrayList.get(position).getFirstWord().equals(pre) ? View.VISIBLE : View.GONE);
        pre = arrayList.get(position).getFirstWord();
        return convertView;
    }

    class ViewHolder {
        TextView tv_firstWord;
        TextView name;
    }

MainActivity

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private TextView tv_first;
    private ArrayList<Contact> contacts;
    private SlidView slidView;

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

    private void initView() {
        listView = (ListView) findViewById(R.id.friend_listview);
        tv_first = (TextView) findViewById(R.id.tv_first);
        slidView = (SlidView) findViewById(R.id.slidView);
        slidView.setFirstListener(new OnTouchFirstListener() {
            @Override
            public void onTouch(String str) {
                tv_first.setVisibility(View.VISIBLE);
                tv_first.setText(str);
                for (int i = 0; i < contacts.size(); i++) {
                    if (str.equals(contacts.get(i).getFirstWord())) {
                        listView.setSelection(i);
                    }
                }
            }

            @Override
            public void onRelease() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_first.setVisibility(View.GONE);
                    }
                }, 300);
            }
        });
    }

    private void initData() {
        contacts = new ArrayList<>();
        //獲取字元陣列資源
        String[] attrs = getResources().getStringArray(R.array.myFriend);
        Contact contact;
        for (int i = 0; i < attrs.length; i++) {
            contact = new Contact();
            contact.setName(attrs[i]);
            contact.setFirstWord(getPinYinHeadChar(attrs[i], 2));
            contacts.add(contact);
        }
        //排序A-Z
        Collections.sort(contacts, new Comparator<Contact>() {
            @Override
            public int compare(Contact lhs, Contact rhs) {
                return lhs.getFirstWord().compareTo(rhs.getFirstWord());
            }
        });
        ContactAdapter contactAdapter = new ContactAdapter(contacts, this);
        listView.setAdapter(contactAdapter);
    }

    /**
     * 提取漢字的首字母,如果裡面含有費中文字元則忽略之;如果全為非中文則返回""。
     *
     * @param caseType 當為1時獲取的首字母為小寫,否則為大寫。
     */
    public static String getPinYinHeadChar(String zn_str, int caseType) {
        if (zn_str != null && !zn_str.trim().equalsIgnoreCase("")) {
            char[] strChar = zn_str.toCharArray();
            // 漢語拼音格式輸出類
            HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat();
            // 輸出設定,大小寫,音標方式等
            if (1 == caseType) {
                hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            } else {
                hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
            }
            hanYuPinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            hanYuPinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
            StringBuffer pyStringBuffer = new StringBuffer();
            char c = strChar[0];
            char pyc;
            if (String.valueOf(c).matches("[\\u4E00-\\u9FA5]+")) {//是中文或者a-z或者A-Z轉換拼音
                try {
                    String[] pyStirngArray = PinyinHelper.toHanyuPinyinStringArray(strChar[0], hanYuPinOutputFormat);
                    if (null != pyStirngArray && pyStirngArray[0] != null) {
                        pyc = pyStirngArray[0].charAt(0);
                        pyStringBuffer.append(pyc);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }
            return pyStringBuffer.toString();
        }
        return null;
    }

提取首字母需要用到pingyin4j.jar,小編在這不提供,大家可以在網上下載

//自定義字母導航控制元件
public class SlidView extends View {
    private String[] strs = {"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 paint;
    private OnTouchFirstListener listener;

    public SlidView(Context context) {
        this(context, null);
    }

    public SlidView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.GRAY);
        paint.setTypeface(Typeface.DEFAULT_BOLD);

    }

    //  px---->sp
    protected int sp2px(int spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < strs.length; i++) {
            paint.setColor(i == index ? Color.RED : Color.BLACK);
            paint.setTextSize(i == index ? sp2px(18) : sp2px(16));
            int x = (int) (getWidth() - paint.measureText(strs[i])) / 2;
            int y = getHeight() / strs.length * (i + 1);
            canvas.drawText(strs[i], x, y, paint);
        }
    }

    int index = -1;  //獲取觸控到字母索引的位置

    //觸碰事件
    //按下,鬆開,拖動
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                float y = event.getY();
                this.setBackgroundColor(Color.GRAY);
                //獲取觸控到字母的位置
                index = (int) y * strs.length / getHeight();
                listener.onTouch(strs[index]);
                break;
            case MotionEvent.ACTION_UP:
                this.setBackgroundColor(android.R.color.transparent);
                index = -1;
                listener.onRelease();
                break;
        }
        //重繪
        invalidate();
        return true;
    }

    public void setFirstListener(OnTouchFirstListener listener) {
        this.listener = listener;
    }
}
/**
 * OnTouchFirstListener 介面
 * onTouch:觸控到了那個字母
 * onRelease:up釋放時中間顯示的字母需要設定為GONE
 */
public interface OnTouchFirstListener {
    void onTouch(String ch);
    void onRelease();
}