1. 程式人生 > >輸入框傳送表情(本地)

輸入框傳送表情(本地)

表情是一些特定的組合,如f000,f001等

/**
     * 顯示內容
     * @param msg
     * @return
     */
    private SpannableString convertContent(String msg){
        String emoji;
        String regex = "f0[0-9]{2}|f10[0-6]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(msg);
        SpannableString spannableString = new
SpannableString(msg); int totalLen = 0; String leftString = msg.substring(0, msg.length()); //找到一個匹配的,就擷取 while(matcher.find(0)){ emoji = matcher.group(); if(emoji.length() > 0){ //找到表情在這段字串的位置 int len = leftString.indexOf(emoji)+emoji.length(); //記錄總長度
totalLen = totalLen + len; Log.e("ZYL", "emoji:"+emoji+" ,len:"+len +", totalLen: "+totalLen); //轉化為表情 getSpannableString(spannableString, emoji,totalLen); //剩下字串作為下一段字串 leftString = msg.substring(totalLen, msg.length()); //重置matcher
matcher.reset(leftString); }else{ break; } } return spannableString; } private SpannableString getSpannableString(SpannableString spannableString,String emoji,int totalLen){ try { Field field = R.drawable.class.getDeclaredField(emoji); int imageId = field.getInt(R.drawable.class); //根據圖片的id得到bitmap Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), imageId); //得到ImageSpan ImageSpan imageSpan = new ImageSpan(context,bmp); //使表情的text顯示為表情圖片 spannableString.setSpan(imageSpan, totalLen-emoji.length(), totalLen, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE); return spannableString; } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } return null; }