Chinaunix首页 | 论坛 | 博客
  • 博客访问: 236315
  • 博文数量: 54
  • 博客积分: 2656
  • 博客等级: 少校
  • 技术积分: 1020
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-19 21:06
文章分类

全部博文(54)

文章存档

2016年(3)

2014年(8)

2013年(4)

2012年(2)

2011年(29)

2010年(8)

我的朋友

分类: Java

2011-04-28 14:33:38

在android中短信功能里面就自带了将字符替换成表情的功能,源码中主要的类是:SmileyParser.java

/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.tao.test;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;

//import com.android.mms.R;


import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A class for annotating a CharSequence with spans to convert textual emoticons
 * to graphical ones.
 */

public class SmileyParser {
    // Singleton stuff

    private static SmileyParser sInstance;
    public static SmileyParser getInstance() { return sInstance; }
    public static void init(Context context) {
        sInstance = new SmileyParser(context);
    }

    private final Context mContext;
    private final String[] mSmileyTexts;
    private final Pattern mPattern;
    private final HashMap<String, Integer> mSmileyToRes;

    private SmileyParser(Context context) {
        mContext = context;
        mSmileyTexts = mContext.getResources().getStringArray(DEFAULT_SMILEY_TEXTS);
        mSmileyToRes = buildSmileyToRes();
        mPattern = buildPattern();
    }

    static class Smileys {
        private static final int[] sIconIds = {
            R.drawable.emo_im_happy,
            R.drawable.emo_im_sad,
            R.drawable.emo_im_winking,
            R.drawable.emo_im_tongue_sticking_out,
            R.drawable.emo_im_surprised,
            R.drawable.emo_im_kissing,
            R.drawable.emo_im_yelling,
            R.drawable.emo_im_cool,
            R.drawable.emo_im_money_mouth,
            R.drawable.emo_im_foot_in_mouth,
            R.drawable.emo_im_embarrassed,
            R.drawable.emo_im_angel,
            R.drawable.emo_im_undecided,
            R.drawable.emo_im_crying,
            R.drawable.emo_im_lips_are_sealed,
            R.drawable.emo_im_laughing,
            R.drawable.emo_im_wtf
        };

        public static int HAPPY = 0;
        public static int SAD = 1;
        public static int WINKING = 2;
        public static int TONGUE_STICKING_OUT = 3;
        public static int SURPRISED = 4;
        public static int KISSING = 5;
        public static int YELLING = 6;
        public static int COOL = 7;
        public static int MONEY_MOUTH = 8;
        public static int FOOT_IN_MOUTH = 9;
        public static int EMBARRASSED = 10;
        public static int ANGEL = 11;
        public static int UNDECIDED = 12;
        public static int CRYING = 13;
        public static int LIPS_ARE_SEALED = 14;
        public static int LAUGHING = 15;
        public static int WTF = 16;

        public static int getSmileyResource(int which) {
            return sIconIds[which];
        }
    }

    // NOTE: if you change anything about this array, you must make the corresponding change

    // to the string arrays: default_smiley_texts and default_smiley_names in res/values/arrays.xml

    public static final int[] DEFAULT_SMILEY_RES_IDS = {
        Smileys.getSmileyResource(Smileys.HAPPY), // 0

        Smileys.getSmileyResource(Smileys.SAD), // 1

        Smileys.getSmileyResource(Smileys.WINKING), // 2

        Smileys.getSmileyResource(Smileys.TONGUE_STICKING_OUT), // 3

        Smileys.getSmileyResource(Smileys.SURPRISED), // 4

        Smileys.getSmileyResource(Smileys.KISSING), // 5

        Smileys.getSmileyResource(Smileys.YELLING), // 6

        Smileys.getSmileyResource(Smileys.COOL), // 7

        Smileys.getSmileyResource(Smileys.MONEY_MOUTH), // 8

        Smileys.getSmileyResource(Smileys.FOOT_IN_MOUTH), // 9

        Smileys.getSmileyResource(Smileys.EMBARRASSED), // 10

        Smileys.getSmileyResource(Smileys.ANGEL), // 11

        Smileys.getSmileyResource(Smileys.UNDECIDED), // 12

        Smileys.getSmileyResource(Smileys.CRYING), // 13

        Smileys.getSmileyResource(Smileys.LIPS_ARE_SEALED), // 14

        Smileys.getSmileyResource(Smileys.LAUGHING), // 15

        Smileys.getSmileyResource(Smileys.WTF), // 16

    };

    public static final int DEFAULT_SMILEY_TEXTS = R.array.default_smiley_texts;
    public static final int DEFAULT_SMILEY_NAMES = R.array.default_smiley_names;

    /**
     * Builds the hashtable we use for mapping the string version
     * of a smiley (e.g. ":-)") to a resource ID for the icon version.
     */

    private HashMap<String, Integer> buildSmileyToRes() {
        if (DEFAULT_SMILEY_RES_IDS.length != mSmileyTexts.length) {
            // Throw an exception if someone updated DEFAULT_SMILEY_RES_IDS

            // and failed to update arrays.xml

            throw new IllegalStateException("Smiley resource ID/text mismatch");
        }

        HashMap<String, Integer> smileyToRes =
                            new HashMap<String, Integer>(mSmileyTexts.length);
        for (int i = 0; i < mSmileyTexts.length; i++) {
            smileyToRes.put(mSmileyTexts[i], DEFAULT_SMILEY_RES_IDS[i]);
        }

        return smileyToRes;
    }

    /**
     * Builds the regular expression we use to find smileys in {@link #addSmileySpans}.
     */

    private Pattern buildPattern() {
        // Set the StringBuilder capacity with the assumption that the average

        // smiley is 3 characters long.

        StringBuilder patternString = new StringBuilder(mSmileyTexts.length * 3);

        // Build a regex that looks like (:-)|:-(|...), but escaping the smilies

        // properly so they will be interpreted literally by the regex matcher.

        patternString.append('(');
        for (String s : mSmileyTexts) {
            patternString.append(Pattern.quote(s));
            patternString.append('|');
        }
        // Replace the extra '|' with a ')'

        patternString.replace(patternString.length() - 1, patternString.length(), ")");

        return Pattern.compile(patternString.toString());
    }


    /**
     * Adds ImageSpans to a CharSequence that replace textual emoticons such
     * as :-) with a graphical version.
     *
     * @param text A CharSequence possibly containing emoticons
     * @return A CharSequence annotated with ImageSpans covering any
     * recognized emoticons.
     */

    public CharSequence addSmileySpans(CharSequence text) {
        SpannableStringBuilder builder = new SpannableStringBuilder(text);

        Matcher matcher = mPattern.matcher(text);
        while (matcher.find()) {
            int resId = mSmileyToRes.get(matcher.group());
            builder.setSpan(new ImageSpan(mContext, resId),
                            matcher.start(), matcher.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        return builder;
    }
}


主要有配置文件:arrays.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!--
 * Copyright (C) 2008 Esmertec AG.
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
  -->

<resources xmlns:android=""
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string-array name="default_smiley_texts">
    <item msgid="6418813270603201918">":-)"</item>
    <item msgid="5037069969500587717">":-("</item>
    <item msgid="1706022067142803863">";-)"</item>
    <item msgid="1248733150365342132">":-P"</item>
    <item msgid="817475806953665071">"=-O"</item>
    <item msgid="2791428909459014455">":-*"</item>
    <item msgid="3521914049512875091">":O"</item>
    <item msgid="1245726345240784103">"B-)"</item>
    <item msgid="6236841507652113784">":-$"</item>
    <item msgid="9041518876704445176">":-!"</item>
    <item msgid="5938573563873054892">":-["</item>
    <item msgid="662834190186827918">"O:-)"</item>
    <item msgid="8667007781479284572">":-\\"</item>
    <item msgid="6895634303037073990">":\'("</item>
    <item msgid="3660685022708121640">":-X"</item>
    <item msgid="2893940139682468617">":-D"</item>
    <item msgid="4888792634429693183">"o_O"</item>
  </string-array>
  <string-array name="default_smiley_names">
    <item msgid="1831934949361041701">"开心"</item>
    <item msgid="1601611480575517120">"忧伤"</item>
    <item msgid="1531181614218625881">"眨眼"</item>
    <item msgid="3858808057949077894">"吐舌"</item>
    <item msgid="7835238297967185651">"惊讶"</item>
    <item msgid="1756223535005296033">"亲吻"</item>
    <item msgid="1093906245140165107">"叫喊"</item>
    <item msgid="888834839864150170">"酷"</item>
    <item msgid="6320683740534773967">"财迷"</item>
    <item msgid="6610111212478853990">"说错了话"</item>
    <item msgid="1706035208563940251">"尴尬"</item>
    <item msgid="9079275787422313427">"天使"</item>
    <item msgid="4630490399784004880">"犹豫"</item>
    <item msgid="7002574538342357456">"哭泣"</item>
    <item msgid="850324578089267455">"保密"</item>
    <item msgid="6334637439528489607">"大笑"</item>
    <item msgid="7602915122893958066">"困惑"</item>
  </string-array>
</resources>


实现效果如图:
阅读(3001) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~