編輯:關於 Android 程式設計
前言
真正動手寫聊天功能才發現,程式碼積累的價值。這篇記錄的其實沒什麼高難度,瑣碎但耗時間——而這正是積累的意義:寫過一次整理下來,下次直接拿來用,不必重新摸索。否則下次遇到同樣需求,又得從零開始踩一遍坑。
Demo 展示

功能是仿微信的聊天表情選擇面板,採 ViewPager + GridView 的組合方案。至於在 TextView / EditText 中顯示表情圖示,一般有兩條路:用 Html.fromHtml 解析,或直接用 Bitmap 繪製。這裡採用後者。
思路
既然是 ViewPager 裝 GridView,就先把 ViewPager 搭起來,再往裡填 GridView。程式碼中用到 RxJava、lambda、ButterKnife、EventBus、Glide。
整個底部區域封裝成一個組合 ViewGroup —— ChatBottomBar,先從布局看起。
ChatBottomBar 的 XML(chat_bottom.xml):
<?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="wrap_content" android:animateLayoutChanges="true" android:orientation="vertical"> <include layout="@layout/chat_bottom_input"></include> <include layout="@layout/chat_bottom_function1"></include> </LinearLayout>
輸入框部分(chat_bottom_input):
<?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:id="@+id/rl_input" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#f0f0f0"> <ImageView android:id="@+id/showMore" android:layout_width="42dp" android:layout_height="60dp" android:paddingBottom="5dp" android:paddingLeft="9dp" android:paddingTop="9dp" android:src="@mipmap/ic_launcher" /> <LinearLayout android:layout_width="match_parent" android:layout_height="35dp" android:layout_centerVertical="true" android:layout_marginRight="15dp" android:layout_toRightOf="@+id/showMore" android:background="@drawable/shape_white_corner" android:gravity="center_vertical" android:orientation="horizontal"> <ImageView android:layout_width="45dp" android:layout_height="40dp" android:paddingBottom="10dp" android:paddingLeft="10dp" android:paddingRight="5dp" android:paddingTop="10dp" android:src="@mipmap/ic_launcher" /> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginRight="10dp" android:background="@null" android:gravity="center_vertical" android:hint="說點什麼" android:maxLines="3" android:textColor="#999999" android:textColorHint="#dddddd" android:textSize="13sp" /> </LinearLayout> </RelativeLayout> </merge>
表情面板部分(chat_bottom_function1):
<?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="wrap_content" android:background="#ffffff" android:orientation="vertical"> <android.support.v4.view.ViewPager android:id="@+id/emojes" android:layout_width="match_parent" android:layout_height="110dp"></android.support.v4.view.ViewPager> </LinearLayout>
ViewPager 填充 GridView
先看 PagerAdapter 需要什麼資料——答案很單純,就是一堆 GridView:
package cjh.emojicondemo; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.GridView; import java.util.ArrayList; /** * Created by cjh on 16-11-8. */ public class EmojiPageAdapter extends PagerAdapter { private ArrayList<GridView> mLists; public EmojiPageAdapter(Context context, ArrayList<GridView> array) { this.mLists = array; } @Override public int getCount() { return mLists.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public Object instantiateItem(View arg0, int arg1) { ((ViewPager) arg0).addView(mLists.get(arg1)); return mLists.get(arg1); } @Override public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); } }
基本上就是 PagerAdapter 的範本程式碼。接著在 ChatBottomBar 中建立各頁:
@BindView(R.id.emojes) android.support.v4.view.ViewPager emojes; .... //每一頁有24個表情,然後使用Math的ceil函數,計算出我們需要的最小頁數 private void initEmoje() { int pageCount = (int) Math.ceil(EmojiUtils.emojis.length / 24.0f); ArrayList<GridView> pageData = new ArrayList<>(); for (int i = 0; i < pageCount; i++) { GridView gv = getGridView(i); pageData.add(gv); } emojes.setAdapter(new EmojiPageAdapter(context, pageData)); }
GridVie w 的建立:
@NonNull private GridView getGridView(int i) { GridView gv = new GridView(context); gv.setVerticalScrollBarEnabled(false); gv.setAdapter(new EmojiGridAdapter(context, i)); gv.setGravity(Gravity.CENTER); gv.setClickable(true); gv.setFocusable(true); gv.setNumColumns(8); return gv; }
對應的 adapter:
package cjh.emojicondemo; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import org.greenrobot.eventbus.EventBus; /** * Created by cjh on 16-11-8. */ public class EmojiGridAdapter extends BaseAdapter { private Context context; private int page; public EmojiGridAdapter(Context context, int page) { this.context = context; this.page = page; } @Override public int getCount() { return 24; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder = null; if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.chat_emoji, null); holder = new ViewHolder(); holder.image = (ImageView) view.findViewById(R.id.image); view.setTag(holder); } holder = (ViewHolder) view.getTag(); int position = page * 23 + i; if (position < EmojiUtils.emojis.length) ImageLoader.load(context, EmojiUtils.icons[position], holder.image); else holder.image.setVisibility(View.GONE); holder.image.setOnClickListener(view1 -> EventBus.getDefault().post(new EmojiEvent(EmojiUtils.emojis[page * 23 + i]))); return view; } static class ViewHolder { public ImageView image; } }
點擊事件透過 EventBus 拋出去,避免層層回呼介面。接收端:
@Subscribe public void onEmojiEvent(EmojiEvent emojiEvent) { chatBottomBar.appandEmoje(emojiEvent.s); }
回到 ChatBottomBar 的插入邏輯:
public void appandEmoje(String s) { rx.Observable .just(s) .subscribeOn(Schedulers.io()) .map(s1 -> { SpannableString emojeText = EmojiUtils.getEmojiText(editText.getText().toString() + s1); return emojeText; }) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(s2 -> { editText.setText(""); editText.append(s2); }); }
真正的核心落在 EmojiUtils.getEmojiText()。為什麼要用 RxJava 包一層?因為這個方法要對整段文字做正則遍歷比對,字一多就明顯卡頓,丟到 io 執行緒再切回主執行緒更新 UI 是必要的。
EmojiUtils 實作:
package cjh.emojicondemo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ImageSpan; import android.text.style.RelativeSizeSpan; import android.util.SparseArray; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.Inflater; /** * Created by cjh on 16-11-7. */ public class EmojiUtils { private static HashMap<Pattern, Integer> emoMap = new HashMap<>(); public static final String DELETE_KEY = "em_delete_delete_expression"; public static String[] emojis = new String[]{ "[微笑]", "[撇嘴]", "[色]", "[發呆]", "[得意]", "[流淚]", "[害羞]", "[閉嘴]", "[睡]", "[大哭]", "[尴尬]", "[發怒]", "[調皮]", "[呲牙]", "[驚訝]", "[難過]", "[酷]", "[冷汗]", "[抓狂]", "[吐]", "[偷笑]", "[愉快]", "[白眼]", "[傲慢]", "[饑餓]", "[困]", "[驚恐]", "[流汗]", "[憨笑]", "[悠閒]", "[奮斗]", "[咒罵]", "[疑問]", "[噓]", "[暈]", "[瘋了]", "[衰]", "[骷髅]", "[敲打]", "[再見]", "[擦汗]", "[摳鼻]", "[鼓掌]", "[糗大了]", "[壞笑]", "[左哼哼]", "[右哼哼]", "[哈欠]", "[鄙視]", "[委屈]", "[快哭了]", "[陰險]", "[親親]", "[嚇]", "[可憐]", "[菜刀]", "[西瓜]", "[啤酒]", "[籃球]", "[乒乓]", "[咖啡]", "[飯]", "[豬頭]", "[玫瑰]", "[凋謝]", "[嘴唇]", "[愛心]", "[心碎]", "[蛋糕]", "[閃電]", "[炸彈]", "[刀]", "[足球]", "[瓢蟲]", "[便便]", "[月亮]", "[太陽]", "[禮物]", "[擁抱]", "[強]", "[弱]", "[握手]", "[勝利]", "[抱拳]", "[勾引]", "[拳頭]", "[差勁]", "[愛你]", "[NO]", "[OK]" }; public static int[] icons = new int[]{ R.drawable.ee_1, R.drawable.ee_2, R.drawable.ee_3, R.drawable.ee_4, R.drawable.ee_5, R.drawable.ee_6, R.drawable.ee_7, R.drawable.ee_8, R.drawable.ee_9, R.drawable.ee_10, R.drawable.ee_11, R.drawable.ee_12, R.drawable.ee_13, R.drawable.ee_14, R.drawable.ee_15, R.drawable.ee_16, R.drawable.ee_17, R.drawable.ee_18, R.drawable.ee_19, R.drawable.ee_20, R.drawable.ee_21, R.drawable.ee_22, R.drawable.ee_23, R.drawable.ee_24, R.drawable.ee_25, R.drawable.ee_26, R.drawable.ee_27, R.drawable.ee_28, R.drawable.ee_29, R.drawable.ee_30, R.drawable.ee_31, R.drawable.ee_32, R.drawable.ee_33, R.drawable.ee_34, R.drawable.ee_35, R.drawable.ee_36, R.drawable.ee_37, R.drawable.ee_38, R.drawable.ee_39, R.drawable.ee_40, R.drawable.ee_41, R.drawable.ee_42, R.drawable.ee_43, R.drawable.ee_44, R.drawable.ee_45, R.drawable.ee_46, R.drawable.ee_47, R.drawable.ee_48, R.drawable.ee_49, R.drawable.ee_50, R.drawable.ee_51, R.drawable.ee_52, R.drawable.ee_53, R.drawable.ee_54, R.drawable.ee_55, R.drawable.ee_56, R.drawable.ee_57, R.drawable.ee_58, R.drawable.ee_59, R.drawable.ee_60, R.drawable.ee_61, R.drawable.ee_62, R.drawable.ee_63, R.drawable.ee_64, R.drawable.ee_65, R.drawable.ee_66, R.drawable.ee_67, R.drawable.ee_68, R.drawable.ee_69, R.drawable.ee_70, R.drawable.ee_71, R.drawable.ee_72, R.drawable.ee_73, R.drawable.ee_74, R.drawable.ee_75, R.drawable.ee_76, R.drawable.ee_77, R.drawable.ee_78, R.drawable.ee_79, R.drawable.ee_80, R.drawable.ee_81, R.drawable.ee_82, R.drawable.ee_83, R.drawable.ee_84, R.drawable.ee_85, R.drawable.ee_86, R.drawable.ee_87, R.drawable.ee_88, R.drawable.ee_89, R.drawable.ee_90, }; static { for (int i = 0; i < emojis.length; i++) { emoMap.put(Pattern.compile(Pattern.quote(emojis[i])), icons[i]); } } public static SpannableString getEmojiText(String s) { SpannableString spannable = new SpannableString(s); for (Map.Entry<Pattern, Integer> entry : emoMap.entrySet()) { Matcher matcher = entry.getKey().matcher(spannable); while (matcher.find()) { for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) if (spannable.getSpanStart(span) >= matcher.start() && spannable.getSpanEnd(span) <= matcher.end()) spannable.removeSpan(span); else break; Drawable drawable = MainActivity.context.getResources().getDrawable(entry.getValue()); drawable.setBounds(0, 0, 60, 60); ImageSpan imageSpan = new ImageSpan(drawable); spannable.setSpan(imageSpan, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } return spannable; } }
這裡的做法是把表情對應的中文佔位符(例如 [微笑])預先編成正則 Pattern,getEmojiText 中遍歷比對,命中就替換成 ImageSpan。要注意 Pattern.quote() 是必需的,因為佔位符裡含 [] 這類正則元字元,不轉義會直接拋 PatternSyntaxException。另外那個「先移除區間內舊 span 再加新 span」的迴圈,是為了避免同一位置堆疊多個 ImageSpan 導致顯示錯亂。
還有一處值得注意的實作瑕疵:程式碼中 getCount() 固定回傳 24,但位置換算卻用 page * 23 + i。每頁 24 格卻只推進 23,會造成跨頁時有一格重複、一格遺漏。這類邊界錯誤在分頁列表裡很常見,建議統一抽成常數避免寫死。
原始碼:https://github.com/cjhandroid/EmojiInputDemo
以上就是本文的全部內容,希望對大家有所幫助。
Android 頭像設定實作教學:相簿選圖與相機拍照裁剪全流程
幾乎每一款 App 在註冊或個人資料頁面都離不開「設定頭像」這個環節。實務上常見的做法大致可以歸成三類: (1)打開手機相簿挑一張舊照片,裁切成正方形後當頭像; (2)直
友盟 5.0 推送與分享踩坑總結
友盟 5.0 的變化 友盟 5.0 相較於舊版,推送與分享可以透過 Module 形式整合,資源與程式碼都更精簡。不過剛改版時,常會遇到與舊版不同的配置方式,因此需要重新
透徹理解Android Service:基礎知識與編寫實戰
首先,什麼是Service? Service就是Android系統中的服務,它有這麼幾個特點:它無法與使用者直接交互,必須由使用者或其他程式顯式啟動;它的優先級比較高——
Android 快速實現夜間模式的簡單方法實例詳解
ChangeMode 專案地址:ChangeMode 為 Android 實現夜間模式。 用最簡單的方式實現夜間模式,支援 ListView、RecyclerView。