編輯:關於 Android 程式設計
微信通訊錄右側那條 A-Z 的細窄索引欄,手指滑到哪裡,屏幕中間就浮出一個大字母,列表同時跳到對應位置——這個交互幾乎成了通訊錄類頁面的標配。本文拆解它的實現。
效果預覽:

整體拆成四步:
1. 搭建整體佈局
2. 實現 A-Z 分組顯示
3. 自定義 A-Z 索引欄
4. 觸摸時在屏幕中間顯示/隱藏對應字母
用 FrameLayout 把列表、中央字母提示、右側索引欄三層疊在一起。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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>
每個 item 由兩部分組成:灰色的分組標題和具體的聯繫人名稱。分組標題並非每一項都顯示,這由適配器控制。
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; } }
分組的思路很巧妙:用一個成員變量 pre 記住上一項的首字母,當前項與它不同時才顯示標題。由於數據已按首字母排序,相同字母必然相鄰,這樣一遍遍歷就能完成分組。
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; }
這裡有個隱患值得指出:由於 ListView 複用 convertView,而 pre 是唯一的成員變量,快速滑動時 getView 的調用順序雖仍按位置遞增,但一旦引入非同步的分支加載就可能出錯。更穩健的做法是直接比較 position 與 position - 1 的首字母,不依賴外部狀態。
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; }
提取首字母依賴 pinyin4j 這個 jar 包(網上可自行下載)。核心邏輯是判斷首字符是否為漢字,若是則轉成拼音並取第一個字母,否則返回空串。數據準備好後按首字母排序,分組才能成立。
還有一個細節:中央提示字母在手指抬起後延遲 300 毫秒才隱藏,短暫的停留讓用戶看得清自己點到了哪個字母,比立刻消失要舒服。
//自定義字母導航控件 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(); }
這個自定義 View 的實現要點:
索引計算。index = (int) y * strs.length / getHeight(),用觸摸的 y 坐標按比例映射到 0-25 的索引。這種算法與屏幕分辨率無關,天然自適配。
繪製時的視覺反饋。被觸摸的那個字母會變紅並放大兩號,同時整個背景變灰,讓用戶明確感知當前位置。
接口回調解耦。索引欄只負責算出「點到了哪個字母」,至於字母提示怎麼顯示、列表怎麼跳,全部交給外部通過 OnTouchFirstListener 處理,這讓組件具備了複用價值。
實踐中還可以優化的地方:一是給索引欄加一個 onMeasure 保證高度足夠(26 個字母在小屏上會擠);二是把 contacts 的首字母預先建一個索引表(記錄每個字母首次出現的位置),把 onTouch 裡的 O(n) 遍歷降到 O(1),列表長時效果明顯。
以上就是本文的全部內容,希望對大家的學習有所幫助。
打造強大的 Android 日誌工具類 LogUtils
在開發中,我們常常透過打印 log 來調試應用。Java 中常用 System.out.println() 在控制台輸出日誌,而 Android 則提供了專門的 Log
開源元件 GridViewWithHeaderAndFooter 使用與原始碼解析
GridViewWithHeaderAndFooter 這個元件,讓你能像使用 ListView 一樣,為 GridView 加上 Header 與 Footer。專案網
Activity 跳轉 Flag 全攻略:Intent 標記與 Task 屬性一次講透
Android 有個相當特別的設計:Application A 的 Activity 可以啟動 Application B 的 Activity,即便兩者毫不相干,使用者
CodeIgniter + Volley 實現多圖片上傳(含服務端、Web 與 Android 完整代碼)
問題背景:App 在加載圖片時,往往還需要同時傳遞參數,並支持一次上傳多張圖片。本文以已配好 CodeIgniter 框架的服務端為例(不用該框架其實也無妨),完整演示服