Android學習筆記:完整實例實現QQ表情的發送和接收

  
在自己做一個聊天應用練習的時候,需要用到表情,於是就想著模仿一下QQ表情,圖片資源完全copy的QQ.apk,解壓就可以得到,這裡不細說。
下面將該應用中的表情模塊功能抽離出來,以便自己以後復習回顧。。
先看一下效果圖:
首先進入界面:(完全仿照QQ)
 
 
點擊一下上面的表情圖標:
 
選擇一些表情,輸入一些文字混合:
 
點擊發送:
 
可以看到文字和表情圖片都一起顯示出來瞭。
 
下面列出一些關鍵代碼:
表情工具類ExpressionUtil:
[java]
public class ExpressionUtil { 
    /**
     * 對spanableString進行正則判斷,如果符合要求,則以表情圖片代替
     * @param context
     * @param spannableString
     * @param patten
     * @param start
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws NumberFormatException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */ 
    public static void dealExpression(Context context,SpannableString spannableString, Pattern patten, int start) throws SecurityException, NoSuchFieldException, NumberFormatException, IllegalArgumentException, IllegalAccessException { 
        Matcher matcher = patten.matcher(spannableString); 
        while (matcher.find()) { 
            String key = matcher.group(); 
            if (matcher.start() < start) { 
                continue; 
            } 
            Field field = R.drawable.class.getDeclaredField(key); 
            int resId = Integer.parseInt(field.get(null).toString());       //通過上面匹配得到的字符串來生成圖片資源id 
            if (resId != 0) { 
                Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId);     
                ImageSpan imageSpan = new ImageSpan(bitmap);                //通過圖片資源id來得到bitmap,用一個ImageSpan來包裝 
                int end = matcher.start() + key.length();                   //計算該圖片名字的長度,也就是要替換的字符串的長度 
                spannableString.setSpan(imageSpan, matcher.start(), end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);   //將該圖片替換字符串中規定的位置中 
                if (end < spannableString.length()) {                        //如果整個字符串還未驗證完,則繼續。。 
                    dealExpression(context,spannableString,  patten, end); 
                } 
                break; 
            } 
        } 
    } 
     
    /**
     * 得到一個SpanableString對象,通過傳入的字符串,並進行正則判斷
     * @param context
     * @param str
     * @return
     */ 
    public static SpannableString getExpressionString(Context context,String str,String zhengze){ 
        SpannableString spannableString = new SpannableString(str); 
        Pattern sinaPatten = Pattern.compile(zhengze, Pattern.CASE_INSENSITIVE);        //通過傳入的正則表達式來生成一個pattern 
        try { 
            dealExpression(context,spannableString, sinaPatten, 0); 
        } catch (Exception e) { 
            Log.e("dealExpression", e.getMessage()); 
        } 
        return spannableString; 
    } 
     
 

 
在顯示聊天頁面的list的適配器中,我們需要做如下的顯示,即調用上面工具類的方法:
SimpleChatAdapter中的內部類ViewHolder:
[java]
private class ViewHolder{ 
        RelativeLayout chat_layout; 
        ImageView image; 
        TextView text; 
        public ViewHolder(View convertView){ 
            chat_layout=(RelativeLayout) convertView.findViewById(R.id.team_singlechat_id_listiteam); 
            image=(ImageView) convertView.findViewById(R.id.team_singlechat_id_listiteam_headicon); 
            text=(TextView) convertView.findViewById(R.id.team_singlechat_id_listiteam_message); 
        } 
        public void setData(MessageInfo msg){ 
            RelativeLayout.LayoutParams rl_chat_left=((RelativeLayout.LayoutParams)chat_layout.getLayoutParams()); 
            RelativeLayout.LayoutParams rl_tv_msg_left=((RelativeLayout.LayoutParams)text.getLayoutParams()); 
            RelativeLayout.LayoutParams rl_iv_headicon_left=((RelativeLayout.LayoutParams)image.getLayoutParams()); 
            if(!DicqConstant.DEFAULTMAC.equalsIgnoreCase(msg.getUsermac())){    //根據本地的mac地址來判斷該條信息是屬於本人所說還是對方所說 
                                                                                //如果是自己說的,則顯示在右邊;如果是對方所說,則顯示在左邊 
                rl_chat_left.addRule(RelativeLayout.ALIGN_PARENT_LEFT,-1); 
                rl_chat_left.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,0); 
                rl_iv_headicon_left.addRule(RelativeLayout.ALIGN_PARENT_LEFT,-1); 
                rl_iv_headicon_left.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,0); 
                rl_tv_msg_left.addRule(RelativeLayout.RIGHT_OF,R.id.team_singlechat_id_listiteam_headicon); 
                rl_tv_msg_left.addRule(RelativeLayout.LEFT_OF,0); 
                text.setBackgroundResource(R.drawable.balloon_l_selector); 
            }else{ 
                rl_chat_left.addRule(RelativeLayout.ALIGN_PARENT_LEFT,0); 
                rl_chat_left.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,-1); 
                rl_iv_headicon_left.addRule(RelativeLayout.ALIGN_PARENT_LEFT,0); 
                rl_iv_headicon_left.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,-1); 
                rl_tv_msg_left.addRule(RelativeLayout.RIGHT_OF,0); 
                rl_tv_msg_left.addRule(RelativeLayout.LEFT_OF,R.id.team_singlechat_id_listiteam_headicon); 
                text.setBackgroundResource(R.drawable.balloon_r_selector); 
            } 
            image.setImageResource(PrortaitUtils.conversionIdToRes(msg.getProtrait()));     //設置頭像 
            String str = msg.getMsg();                                                      //消息具體內容 
            String zhengze = "f0[0-9]{2}|f10[0-7]";                                         //正則表達式,用來判斷消息內是否有表情 
            try { 
                SpannableString spannableString = ExpressionUtil.getExpressionString(context, str, zhengze); 
                text.setText(spannableString); 
            } catch (NumberFormatException e) { 
                e.printStackTrace(); 
            } catch (SecurityException e) { 
                e.printStackTrace(); 
            } catch (IllegalArgumentException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
 
關於表情彈出框的實現如下:
MainActivity:
[java]
/**
     * 創建一個表情選擇對話框
     */ 
    private void createExpressionDialog() { 
        builder = new Dialog(MainActivity.this);  
        GridView gridView = createGridView(); 
        builder.setContentView(gridView); 
        builder.setTitle("默認表情"); 
        builder.show(); 
        gridView.setOnItemClickListener(new OnItemClickListener() { 
             
            @Override 
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
                    long arg3) { 
                Bitmap bitmap = null; 
                bitmap = BitmapFactory.decodeResource(getResources(), imageIds[arg2 % imageIds.length]); 
                ImageSpan imageSpan = new ImageSpan(MainActivity.this, bitmap); 
                String str = null; 
                if(arg2<10){ 
                    str = "f00"+arg2; 
                }else if(arg2<100){ 
                    str = "f0"+arg2; 
                }else{ 
                    str = "f"+arg2; 
                } 
                SpannableString spannableString = new SpannableString(str); 
                spannableString.setSpan(imageSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
                edit.append(spannableString); 
                builder.dismiss(); 
            } 
        }); 
    } 
     
    /**
     * 生成一個表情對話框中的gridview
     * @return
     */ 
    private GridView createGridView() { 
        final GridView view = new GridView(this); 
        List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>(); 
        //生成107個表情的id,封裝 
        for(int i = 0; i < 107; i++){ 
            try { 
                if(i<10){ 
                    Field field = R.drawable.class.getDeclaredField("f00" + i); 
                    int resourceId = Integer.parseInt(field.get(null).toString()); 
                    imageIds[i] = resourceId; 
                }else if(i<100){ 
                    Field field = R.drawable.class.getDeclaredField("f0" + i); 
                    int resourceId = Integer.parseInt(field.get(null).toString()); 
                    imageIds[i] = resourceId; 
                }else{ 
                    Field field = R.drawable.class.getDeclaredField("f" + i); 
                    int resourceId = Integer.parseInt(field.get(null).toString()); 
                    imageIds[i] = resourceId; 
                } 
            } catch (NumberFormatException e) { 
                e.printStackTrace(); 
            } catch (SecurityException e) { 
                e.printStackTrace(); 
            } catch (IllegalArgumentException e) { 
                e.printStackTrace(); 
            } catch (NoSuchFieldException e) { 
                e.printStackTrace(); 
            } catch (IllegalAccessException e) { 
                e.printStackTrace(); 
            } 
            Map<String,Object> listItem = new HashMap<String,Object>(); 
            listItem.put("image", imageIds[i]); 
            listItems.add(listItem); 
        } 
         
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems, R.layout.team_layout_single_expression_cell, new String[]{"image"}, new int[]{R.id.image}); 
        view.setAdapter(simpleAdapter); 
        view.setNumColumns(6); 
        view.setBackgroundColor(Color.rgb(214, 211, 214)); 
        view.setHorizontalSpacing(1); 
        view.setVerticalSpacing(1); 
        view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
        view.setGravity(Gravity.CENTER); 
        return view; 
    } 

作者:duancanmeng

發佈留言