package com.demo.lib.common.emotion; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.text.Spannable; import android.util.AttributeSet; import android.util.Log; import android.widget.EditText; import com.lcjian.lcjianlibrary.R; public class EmotionEditText extends EditText { private int mEmotionSize; private int mEmotionWidth; private int mEmotionHeight; public EmotionEditText(Context context) { super(context); init(null); mEmotionSize = (int) getTextSize(); } public EmotionEditText(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public EmotionEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); } private void init(AttributeSet attrs) { if (attrs == null) { mEmotionSize = (int) getTextSize(); mEmotionWidth = mEmotionSize; mEmotionHeight = mEmotionSize; } else { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Emotion); mEmotionSize = (int) a.getDimension(R.styleable.Emotion_emotionSize, getTextSize()); mEmotionWidth = (int) a.getDimension(R.styleable.Emotion_emotionWidth, 0); mEmotionHeight = (int) a.getDimension(R.styleable.Emotion_emotionWidth, 0); if (mEmotionWidth == 0 || mEmotionHeight == 0) { mEmotionWidth = mEmotionSize; mEmotionHeight = mEmotionSize; } a.recycle(); } setText(getText()); } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { updateText(); } /** * Set the size of emotion in pixels. */ public void setEmotionSize(int pixels) { mEmotionSize = pixels; mEmotionWidth = mEmotionSize; mEmotionHeight = mEmotionSize; updateText(); } public void setEmotionWidth(int pixels) { mEmotionWidth = pixels; updateText(); } public void setEmotionHeight(int pixels) { mEmotionHeight = pixels; updateText(); } private void updateText() { Spannable text = getText(); EmotionSpan[] oldSpans = text.getSpans(0, text.length(), EmotionSpan.class); for (int i = 0; i < oldSpans.length; i++) { text.removeSpan(oldSpans[i]); } Pattern p = Pattern.compile("\\[[^\\[\\]]+\\]"); Matcher m = p.matcher(getText()); while(m.find()){ try { InputStream input = getContext().getAssets().open("emotions" + File.separator + EmotionHandler.faceMap.get(m.group())); if(input != null) { Bitmap bitmap = BitmapFactory.decodeStream(input); EmotionSpan imageSpan = new EmotionSpan(getContext(), bitmap, mEmotionWidth, mEmotionHeight); text.setSpan(imageSpan, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } catch (IOException e) { Log.e("sms", "Failed to loaded content " + m.group(), e); } } } }