Java Code Examples for android.text.style.ImageSpan

The following are top voted examples for showing how to use android.text.style.ImageSpan. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: maud   File: SpanImageListener.java   Source Code and License 8 votes vote down vote up
boolean replace(ImageSpan by) {
    int start = builder.getSpanStart(span);
    int end = builder.getSpanEnd(span);

    if (start == -1)
        return true;

    builder.removeSpan(span);
    builder.setSpan(
            by,
            start,
            end,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    );
    target.setText(builder);
    return true;
}
 
Example 2
Project: cnBetaGeek   File: MyTagHandler.java   Source Code and License 7 votes vote down vote up
@Override
public void handleTag(boolean opening, String tag, Editable output,
		XMLReader xmlReader) {
	// TODO Auto-generated method stub

	// �����ǩ<img>
	if (tag.toLowerCase().equals("img")) {
		// ��ȡ����
		int len = output.length();
		// ��ȡͼƬ��ַ
		ImageSpan[] images = output.getSpans(len-1, len, ImageSpan.class);
		String imgURL = images[0].getSource();
		
		// ʹͼƬ�ɵ������������¼�
		output.setSpan(new ImageClick(context, imgURL), len-1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
	}
}
 
Example 3
Project: GitHub   File: XhsFilter.java   Source Code and License 6 votes vote down vote up
public static void emoticonDisplay(Context context, Spannable spannable, String emoticonName, int fontSize, int start, int end) {
    Drawable drawable = getDrawableFromAssets(context, emoticonName);
    if (drawable != null) {
        int itemHeight;
        int itemWidth;
        if (fontSize == WRAP_DRAWABLE) {
            itemHeight = drawable.getIntrinsicHeight();
            itemWidth = drawable.getIntrinsicWidth();
        } else {
            itemHeight = fontSize;
            itemWidth = fontSize;
        }

        drawable.setBounds(0, 0, itemHeight, itemWidth);
        ImageSpan imageSpan = new ImageSpan(drawable);
        spannable.setSpan(imageSpan, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
}
 
Example 4
Project: airgram   File: GroupCreateActivity.java   Source Code and License 6 votes vote down vote up
private ChipSpan createAndPutChipForUser(TLRPC.User user) {
    LayoutInflater lf = (LayoutInflater) ApplicationLoader.applicationContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View textView = lf.inflate(R.layout.group_create_bubble, null);
    TextView text = (TextView)textView.findViewById(R.id.bubble_text_view);
    String name = UserObject.getUserName(user);
    if (name.length() == 0 && user.phone != null && user.phone.length() != 0) {
        name = PhoneFormat.getInstance().format("+" + user.phone);
    }
    text.setText(name + ", ");

    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    textView.measure(spec, spec);
    textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
    Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(b);
    canvas.translate(-textView.getScrollX(), -textView.getScrollY());
    textView.draw(canvas);
    textView.setDrawingCacheEnabled(true);
    Bitmap cacheBmp = textView.getDrawingCache();
    Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
    textView.destroyDrawingCache();

    final BitmapDrawable bmpDrawable = new BitmapDrawable(b);
    bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight());

    SpannableStringBuilder ssb = new SpannableStringBuilder("");
    ChipSpan span = new ChipSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE);
    allSpans.add(span);
    selectedContacts.put(user.id, span);
    for (ImageSpan sp : allSpans) {
        ssb.append("<<");
        ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    userSelectEditText.setText(ssb);
    userSelectEditText.setSelection(ssb.length());
    return span;
}
 
Example 5
Project: Hitalk   File: TextSpanUtils.java   Source Code and License 6 votes vote down vote up
public static ImageSpan getTextWithBackground(Drawable background, final int textSize
        , final int padding, final int color){
    return new ImageSpan(background){
        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
            paint.setTextSize(textSize + padding);
            int len = Math.round(paint.measureText(text, start, end));
            getDrawable().setBounds(0, 0, len, (int)  (1.5f * getTextMaxHeight(paint,textSize)));

            Drawable b = getDrawable();
            canvas.save();
            int transY = ((bottom-top) - b.getBounds().bottom)/2+top;
            canvas.translate(x , transY);
            b.draw(canvas);
            canvas.restore();

            paint.setColor(color);
            paint.setTextSize(textSize);
            canvas.drawText(text.subSequence(start, end).toString(), x+ padding ,y, paint);
        }
    };
}
 
Example 6
Project: HiBangClient   File: EmoticonsTextView.java   Source Code and License 6 votes vote down vote up
private CharSequence replace(CharSequence text) {
	try {
		SpannableStringBuilder builder = new SpannableStringBuilder(text);
		Pattern pattern = buildPattern();
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			if (BaseApplication.mEmoticonsId.containsKey(matcher.group())) {
				int id = BaseApplication.mEmoticonsId.get(matcher.group());
				Bitmap bitmap = BitmapFactory.decodeResource(
						getResources(), id);
				if (bitmap != null) {
					ImageSpan span = new ImageSpan(getContext(), bitmap);
					builder.setSpan(span, matcher.start(), matcher.end(),
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
			}
		}
		return builder;
	} catch (Exception e) {
		return text;
	}
}
 
Example 7
Project: HiBangClient   File: EmoticonsEditText.java   Source Code and License 6 votes vote down vote up
private CharSequence replace(CharSequence text) {
	try {
		SpannableStringBuilder builder = new SpannableStringBuilder(text);
		Pattern pattern = buildPattern();
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			if (BaseApplication.mEmoticonsId.containsKey(matcher.group())) {
				int id = BaseApplication.mEmoticonsId.get(matcher.group());
				Bitmap bitmap = BitmapFactory.decodeResource(
						getResources(), id);
				if (bitmap != null) {
					ImageSpan span = new ImageSpan(getContext(), bitmap);
					builder.setSpan(span, matcher.start(), matcher.end(),
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
			}
		}
		return builder;
	} catch (Exception e) {
		return text;
	}
}
 
Example 8
Project: SDHtmlTextView   File: ImageHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void handleTagNode(TagNode node, SpannableStringBuilder builder,
		int start, int end, SpanStack stack) {
	String src = node.getAttributeByName("src");

	builder.append("\uFFFC");

	Bitmap bitmap = loadBitmap(src);

	if (bitmap != null) {
		Drawable drawable = new BitmapDrawable(bitmap);
		drawable.setBounds(0, 0, bitmap.getWidth() - 1,
				bitmap.getHeight() - 1);

           stack.pushSpan( new ImageSpan(drawable), start, builder.length() );
	}
}
 
Example 9
Project: FastTextView   File: EllipseFragment.java   Source Code and License 6 votes vote down vote up
@NonNull
  private SpannableStringBuilder getSpannable() {
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(getResources().getString(R.string.content_cn));
    Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
    drawable.setBounds(0, 0, 35, 35);

    spannableStringBuilder.setSpan(new ImageSpan(drawable)
        , 36, 37, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    spannableStringBuilder.setSpan(new ImageSpan(drawable)
        , 37, 38, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    spannableStringBuilder.setSpan(new ImageSpan(drawable)
        , 38, 39, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    spannableStringBuilder.setSpan(new ImageSpan(drawable)
        , 39, 40, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//    ItalicReplacementSpan italicSpan = new ItalicReplacementSpan(-0.25f);
//    StrokeSpan strokeSpan = new StrokeSpan(Color.BLUE, Color.YELLOW, 20);
//    spannableStringBuilder.setSpan(strokeSpan, 0, spannableStringBuilder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    return spannableStringBuilder;
  }
 
Example 10
Project: WeChatDemo   File: EmojiUtil.java   Source Code and License 6 votes vote down vote up
/** 显示文本和表情 */
public static void setText(TextView textView, String text) {
    Context context = textView.getContext();
    Resources resources = context.getResources();
    SpannableString ss = new SpannableString(text);

    // 正则表达式: [高兴]
    Pattern p = Pattern.compile("\\[([A-Za-z\u4E00-\u9FA5]+)\\]");
    Matcher matcher = p.matcher(ss);
    while (matcher.find()) {
        // 匹配到一个表情字符串
        String emoji = matcher.group();
        // 过滤非表情符,比如: [xxx]
        if (EMOJI_DATAS.containsKey(emoji)) {   // 是表情才处理
            // System.out.println("----------" + emoji);
            // 指定了一张图片
            Bitmap bitmap = BitmapFactory.decodeResource(resources, EMOJI_DATAS.get(emoji));
            bitmap = Global.createBitmap(bitmap, Global.dp2px(20));     // 图片的宽高为20dp
            ImageSpan span = new ImageSpan(context, bitmap, ImageSpan.ALIGN_BOTTOM);
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(span, start, end, 0);
        }
    }
    textView.setText(ss);
}
 
Example 11
Project: WeChatDemo   File: EmojiParser.java   Source Code and License 6 votes vote down vote up
public static  SpannableStringBuilder parseEmoji(Context context,String content){
	int size = UIUtils.dip2Px(25,context);
	//里[smiley_00]ff[smiley_78]
	SpannableStringBuilder builder = new SpannableStringBuilder(content);
	//正则表达式
	Pattern pattern = Pattern.compile("\\[smiley_(.*?)\\]");
	Matcher matcher = pattern.matcher(content);
	while(matcher.find()){
		String emo = matcher.group();//[smiley_00]
			emo = emo.substring(1, emo.length()-1);
		//获取表情的id
		int id = context.getResources().getIdentifier(emo, "drawable", context.getPackageName());
		if(id != 0 ){
			Drawable drawable = context.getResources().getDrawable(id);
			// 必须设置图片大小
			drawable.setBounds(0, 0, size, size);
			// 包装一下图片
			ImageSpan span = new ImageSpan(drawable);
			// 把文字替换成图片
			builder.setSpan(span, matcher.start(), matcher.end(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
	return builder;
}
 
Example 12
Project: PocketGopher   File: UnknownPage.java   Source Code and License 6 votes vote down vote up
public void render(final TextView textView, final Context context, String line)
{
    final Handler handler = new Handler(Looper.getMainLooper());
    final SpannableString text = new SpannableString("  " + line + "\n");

    handler.post(new Runnable()
    {
        @Override
        public void run()
        {
            //set the image tag behind (left of) the text
            text.setSpan(new ImageSpan(context, IMAGE_TAG), 0, 1, 0);
            textView.append(text);
        }
    });
}
 
Example 13
Project: boohee_v5.6   File: MQEmotionUtil.java   Source Code and License 6 votes vote down vote up
public static SpannableString getEmotionText(Context context, String source, int
        emotionSizeDp) {
    SpannableString spannableString = new SpannableString(source);
    Matcher matcher = Pattern.compile(REGEX_GROUP).matcher(spannableString);
    if (matcher.find()) {
        matcher.reset();
    }
    while (matcher.find()) {
        String emojiStr = matcher.group(1);
        if (emojiStr != null) {
            ImageSpan imageSpan = getImageSpan(context, emojiStr, emotionSizeDp);
            if (imageSpan != null) {
                int start = matcher.start(1);
                spannableString.setSpan(imageSpan, start, emojiStr.length() + start, 33);
            }
        }
    }
    return spannableString;
}
 
Example 14
Project: HtmlCompat   File: HtmlToSpannedConverter.java   Source Code and License 6 votes vote down vote up
private void startImg(Editable text, Attributes attributes, HtmlCompat.ImageGetter img) {
    String src = attributes.getValue("", "src");
    Drawable d = null;
    if (img != null) {
        d = img.getDrawable(src, attributes);
    }
    if (d == null) {
        Resources res = mContext.getResources();
        d = res.getDrawable(R.drawable.unknown_image);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    }
    int len = text.length();
    text.append("\uFFFC");
    text.setSpan(new ImageSpan(d, src), len, text.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
 
Example 15
Project: LiveGiftLayout   File: ExpressionUtil.java   Source Code and License 6 votes vote down vote up
public SpannableStringBuilder getFace(Context mContext, String content) {
    SpannableStringBuilder sb = new SpannableStringBuilder();
    try {
        /**
         * 经过测试,虽然这里tempText被替换为png显示,但是但我单击发送按钮时,获取到輸入框的内容是tempText的值而不是png
         * 所以这里对这个tempText值做特殊处理
         * 格式:[face/png/f_static_000.png],以方便判斷當前圖片是哪一個
         * */
        String tempText = "[" + content + "]";
        sb.append(tempText);
        sb.setSpan(
                new ImageSpan(mContext, BitmapFactory.decodeStream(mContext.getAssets().open(content))),
                sb.length() - tempText.length(),
                sb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return sb;
}
 
Example 16
Project: decoy   File: ChatRoomMsgViewHolderBaseText.java   Source Code and License 6 votes vote down vote up
@Override
protected void bindContentView() {
    layoutDirection();

    TextView bodyTextView = findViewById(R.id.nim_message_item_text_body);
    bodyTextView.setTextColor(isReceivedMessage() ? Color.BLACK : Color.WHITE);
    bodyTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onItemClick();
        }
    });
    MoonUtil.identifyFaceExpression(NimUIKit.getContext(), bodyTextView, getDisplayText(), ImageSpan.ALIGN_BOTTOM);
    bodyTextView.setMovementMethod(LinkMovementMethod.getInstance());
    bodyTextView.setOnLongClickListener(longClickListener);
}
 
Example 17
Project: decoy   File: IncomingMsgPrompt.java   Source Code and License 6 votes vote down vote up
public void show(IMMessage newMessage) {
    if (newMessageTipLayout == null) {
        init();
    }

    if (!TextUtils.isEmpty(newMessage.getFromAccount())) {
        newMessageTipHeadImageView.loadBuddyAvatar(newMessage.getFromAccount());
    } else {
        newMessageTipHeadImageView.resetImageView();
    }

    MoonUtil.identifyFaceExpression(context, newMessageTipTextView, TeamNotificationHelper.getMsgShowText(newMessage),
            ImageSpan.ALIGN_BOTTOM);
    newMessageTipLayout.setVisibility(View.VISIBLE);
    uiHandler.removeCallbacks(showNewMessageTipLayoutRunnable);
    uiHandler.postDelayed(showNewMessageTipLayoutRunnable, 5 * 1000);
}
 
Example 18
Project: decoy   File: MoonUtil.java   Source Code and License 6 votes vote down vote up
private static SpannableString replaceEmoticons(Context context, String value, float scale, int align) {
	if(TextUtils.isEmpty(value)) {
		value="";
	}
	
	SpannableString mSpannableString = new SpannableString(value);
	Matcher matcher = EmojiManager.getPattern().matcher(value);
	while (matcher.find()) {
		int start = matcher.start();
		int end = matcher.end();
		String emot = value.substring(start, end);
		Drawable d = getEmotDrawable(context, emot, scale);
		if (d != null) {
			ImageSpan span = new ImageSpan(d, align);
			mSpannableString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
	return mSpannableString;
}
 
Example 19
Project: decoy   File: MoonUtil.java   Source Code and License 6 votes vote down vote up
public static void replaceEmoticons(Context context, Editable editable, int start, int count) {
	if (count <= 0 || editable.length() < start + count) 
		return;
	
	CharSequence s = editable.subSequence(start, start + count);
	Matcher matcher = EmojiManager.getPattern().matcher(s);
	while (matcher.find()) {
		int from = start + matcher.start();
		int to = start + matcher.end();
		String emot = editable.subSequence(from, to).toString();
		Drawable d = getEmotDrawable(context, emot, SMALL_SCALE);
		if (d != null) {
			ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
			editable.setSpan(span, from, to, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
}
 
Example 20
Project: decoy   File: AitHelper.java   Source Code and License 6 votes vote down vote up
public static ImageSpan getInputAitSpan(String name, float textsize) {
    if (TextUtils.isEmpty(name)) {
        return null;
    }
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setAntiAlias(true);
    paint.setTextSize(textsize);
    Rect rect = new Rect();

    paint.getTextBounds(name, 0, name.length(), rect);

    // 获取字符串在屏幕上的长度
    int width = (int) (paint.measureText(name));

    final Bitmap bmp = Bitmap.createBitmap(width, rect.height(),
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmp);

    canvas.drawText(name, rect.left, rect.height() - rect.bottom, paint);

    return new ImageSpan(NimUIKit.getContext(), bmp, ImageSpan.ALIGN_BOTTOM);
}
 
Example 21
Project: TurboChat   File: EmojiParser.java   Source Code and License 6 votes vote down vote up
public void insert(SpannableString message) {

        for (String emoji : emojiList) {
            Matcher matcher = getEmojiParser(message.toString(), emoji);
            Bitmap emojiBitmap = null;
            while (matcher.find()) {
                if (emojiBitmap == null) {
                    Resources resources = context.getResources();
                    int resourceId = resources.getIdentifier(String.format("%1s_%2s", emojiResourcePrefix, emoji), EMOJI_TYPE, context.getPackageName());

                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
                    emojiBitmap = Bitmap.createScaledBitmap(bitmap, textSize, textSize, true);
                    bitmap.recycle();
                }
                ImageSpan span = new ImageSpan(context, emojiBitmap, ImageSpan.ALIGN_BASELINE);
                message.setSpan(span, matcher.start(), matcher.end(), 0);
            }
        }

    }
 
Example 22
Project: AyoSunny   File: HtmlTagHandler.java   Source Code and License 6 votes vote down vote up
private static void startImg(SpannableStringBuilder text,
                             Attributes attributes, Html.ImageGetter img) {
    String src = attributes.getValue("", "src");
    Drawable d = null;

    if (img != null) {
        d = img.getDrawable(src);
    }

    if (d == null) {
        d = Resources.getSystem().
                getDrawable(android.R.drawable.ic_delete);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    }

    int len = text.length();
    text.append("\uFFFC");

    text.setSpan(new ImageSpan(d, src), len, text.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
 
Example 23
Project: HX   File: EmojiUtil.java   Source Code and License 6 votes vote down vote up
public static void handlerEmojiText(EditText comment, String content, Context context) throws IOException {
    SpannableStringBuilder sb = new SpannableStringBuilder(content);
    String regex = "\\[(\\S+?)\\]";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(content);
    Iterator<Emoji> iterator;
    Emoji emoji = null;
    while (m.find()) {
        iterator = emojiList.iterator();
        String tempText = m.group();
        while (iterator.hasNext()) {
            emoji = iterator.next();
            if (tempText.equals(emoji.getContent())) {
                //转换为Span并设置Span的大小
                sb.setSpan(new ImageSpan(context, decodeSampledBitmapFromResource(context.getResources(), emoji.getImageUri()
                                , dip2px(context, 18), dip2px(context, 18))),
                        m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            }
        }
    }
    comment.setText(sb);
    comment.setSelection(sb.length());
}
 
Example 24
Project: HX   File: EmojiUtil.java   Source Code and License 6 votes vote down vote up
public static void handlerEmojiText(TextView comment, String content, Context context) throws IOException {
    SpannableStringBuilder sb = new SpannableStringBuilder(content);
    String regex = "\\[(\\S+?)\\]";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(content);
    Iterator<Emoji> iterator;
    Emoji emoji = null;
    while (m.find()) {
        iterator = emojiList.iterator();
        String tempText = m.group();
        while (iterator.hasNext()) {
            emoji = iterator.next();
            if (tempText.equals(emoji.getContent())) {
                //转换为Span并设置Span的大小
                sb.setSpan(new ImageSpan(context, decodeSampledBitmapFromResource(context.getResources(), emoji.getImageUri()
                                , dip2px(context, 50), dip2px(context, 50))),
                        m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            }
        }
    }
    comment.setText(sb);
}
 
Example 25
Project: MyTravelingDiary   File: EmojiUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 讲带emoji表情的字符串解析成带表情的文本
 *
 * @param text
 * @return
 */
public static CharSequence fromStringToEmoji(CharSequence text, Context context) {
    SpannableStringBuilder builder = new SpannableStringBuilder(text);
    Pattern mPattern = Pattern.compile(":(\\S+?):");
    Matcher matcher = mPattern.matcher(text);
    Integer resId = null;
    while (matcher.find()) {
        resId = EmojiTranslate.emojiSrcMap.get(matcher.group(0));
        if (resId != null && resId > 0) {
            Drawable drawable = context.getResources().getDrawable(resId);
            int w = (int) (drawable.getIntrinsicWidth() * 0.32);
            int h = (int) (drawable.getIntrinsicHeight() * 0.32);
            drawable.setBounds(0, 0, w, h);//这里设置图片的大小
            ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
            builder.setSpan(imageSpan, matcher.start(),
                    matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return builder;
}
 
Example 26
Project: MyTravelingDiary   File: EmojiUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 讲带emoji表情的字符串解析成带表情的文本
 *
 * @param text
 * @return
 */

public static CharSequence fromStringToEmoji1(CharSequence text, Context context) {
    SpannableStringBuilder builder = new SpannableStringBuilder(text);
    Pattern mPattern = Pattern.compile(":(\\S+?):");
    Matcher matcher = mPattern.matcher(text);
    Integer resId = null;
    while (matcher.find()) {
        resId = EmojiTranslate.emojiSrcMap.get(matcher.group(0));
        if (resId != null && resId > 0) {
            Drawable drawable = context.getResources().getDrawable(resId);
            int w = (int) (drawable.getIntrinsicWidth() * 0.38);
            int h = (int) (drawable.getIntrinsicHeight() * 0.38);
            drawable.setBounds(0, 0, w, h);//这里设置图片的大小
            ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
            builder.setSpan(imageSpan, matcher.start(),
                    matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return builder;
}
 
Example 27
Project: MyTravelingDiary   File: IncomingMsgPrompt.java   Source Code and License 6 votes vote down vote up
public void show(IMMessage newMessage) {
    if (newMessageTipLayout == null) {
        init();
    }

    if (!TextUtils.isEmpty(newMessage.getFromAccount())) {
        newMessageTipHeadImageView.loadBuddyAvatar(newMessage.getFromAccount());
    } else {
        newMessageTipHeadImageView.resetImageView();
    }

    MoonUtil.identifyFaceExpression(context, newMessageTipTextView, TeamNotificationHelper.getMsgShowText(newMessage),
            ImageSpan.ALIGN_BOTTOM);
    newMessageTipLayout.setVisibility(View.VISIBLE);
    uiHandler.removeCallbacks(showNewMessageTipLayoutRunnable);
    uiHandler.postDelayed(showNewMessageTipLayoutRunnable, 5 * 1000);
}
 
Example 28
Project: MyTravelingDiary   File: MoonUtil.java   Source Code and License 6 votes vote down vote up
private static SpannableString replaceEmoticons(Context context, String value, float scale, int align) {
	if(TextUtils.isEmpty(value)) {
		value="";
	}
	
	SpannableString mSpannableString = new SpannableString(value);
	Matcher matcher = EmojiManager.getPattern().matcher(value);
	while (matcher.find()) {
		int start = matcher.start();
		int end = matcher.end();
		String emot = value.substring(start, end);
		Drawable d = getEmotDrawable(context, emot, scale);
		if (d != null) {
			ImageSpan span = new ImageSpan(d, align);
			mSpannableString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
	return mSpannableString;
}
 
Example 29
Project: MyTravelingDiary   File: MoonUtil.java   Source Code and License 6 votes vote down vote up
public static void replaceEmoticons(Context context, Editable editable, int start, int count) {
	if (count <= 0 || editable.length() < start + count) 
		return;
	
	CharSequence s = editable.subSequence(start, start + count);
	Matcher matcher = EmojiManager.getPattern().matcher(s);
	while (matcher.find()) {
		int from = start + matcher.start();
		int to = start + matcher.end();
		String emot = editable.subSequence(from, to).toString();
		Drawable d = getEmotDrawable(context, emot, SMALL_SCALE);
		if (d != null) {
			ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
			editable.setSpan(span, from, to, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
}
 
Example 30
Project: RxZhihuDaily   File: MoonUtil.java   Source Code and License 6 votes vote down vote up
public static void replaceEmoticons(Context context, Editable editable, int start, int count) {
    if (count <= 0 || editable.length() < start + count)
        return;

    CharSequence s = editable.subSequence(start, start + count);
    Matcher matcher = EmoUtil.getPattern().matcher(s);
    while (matcher.find()) {
        int from = start + matcher.start();
        int to = start + matcher.end();
        String emot = editable.subSequence(from, to).toString();
        Drawable d = getEmotDrawable(context, emot, DEF_SCALE);
        if (d != null) {
            ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
            editable.setSpan(span, from, to, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}
 
Example 31
Project: BiBi   File: FaceTextUtils.java   Source Code and License 6 votes vote down vote up
/**
 * toSpannableString
 * @return SpannableString
 * @throws
 */
public static SpannableString toSpannableString(Context context, String text) {
    if (!TextUtils.isEmpty(text)) {
        SpannableString spannableString = new SpannableString(text);
        int start = 0;
        Pattern pattern = Pattern.compile("\\\\ue[a-z0-9]{3}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            String faceText = matcher.group();
            String key = faceText.substring(1);
            BitmapFactory.Options options = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
                    context.getResources().getIdentifier(key, "drawable", context.getPackageName()), options);
            ImageSpan imageSpan = new ImageSpan(context, bitmap);
            int startIndex = text.indexOf(faceText, start);
            int endIndex = startIndex + faceText.length();
            if (startIndex >= 0)
                spannableString.setSpan(imageSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            start = (endIndex - 1);
        }

        return spannableString;
    } else {
        return new SpannableString("");
    }
}
 
Example 32
Project: BiBi   File: FaceTextUtils.java   Source Code and License 6 votes vote down vote up
public static SpannableString toSpannableString(Context context, String text, SpannableString spannableString) {

        int start = 0;
        Pattern pattern = Pattern.compile("\\\\ue[a-z0-9]{3}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            String faceText = matcher.group();
            String key = faceText.substring(1);
            BitmapFactory.Options options = new BitmapFactory.Options();
//			options.inSampleSize = 2;
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), context.getResources()
                    .getIdentifier(key, "drawable", context.getPackageName()), options);
            ImageSpan imageSpan = new ImageSpan(context, bitmap);
            int startIndex = text.indexOf(faceText, start);
            int endIndex = startIndex + faceText.length();
            if (startIndex >= 0)
                spannableString.setSpan(imageSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            start = (endIndex - 1);
        }

        return spannableString;
    }
 
Example 33
Project: QQ   File: EmoticonsTextView.java   Source Code and License 6 votes vote down vote up
private CharSequence replace(String text) {
	try {
		SpannableString spannableString = new SpannableString(text);
		int start = 0;
		Pattern pattern = buildPattern();
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			String faceText = matcher.group();
			String key = faceText.substring(1);
			BitmapFactory.Options options = new BitmapFactory.Options();
			Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(),
					getContext().getResources().getIdentifier(key, "drawable", getContext().getPackageName()), options);
			ImageSpan imageSpan = new ImageSpan(getContext(), bitmap);
			int startIndex = text.indexOf(faceText, start);
			int endIndex = startIndex + faceText.length();
			if (startIndex >= 0)
				spannableString.setSpan(imageSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			start = (endIndex - 1);
		}
		return spannableString;
	} catch (Exception e) {
		return text;
	}
}
 
Example 34
Project: ChipView   File: ChipView.java   Source Code and License 6 votes vote down vote up
private int buildChip(String chip, SpannableStringBuilder builder, int index, int pos) {
    chipBuilder.setPosition(pos);
    View view = chipBuilder.getChip(inflater, chip);
    int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    view.measure(spec, spec);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmp);
    canvas.translate(-view.getScrollX(), -view.getScrollY());
    view.draw(canvas);
    view.setDrawingCacheEnabled(true);
    Bitmap cache = view.getDrawingCache();
    Bitmap bitmap = cache.copy(Bitmap.Config.ARGB_8888, true);
    view.destroyDrawingCache();
    BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
    drawable.setBounds(0, 0, view.getWidth(), view.getHeight());
    builder.setSpan(new ImageSpan(drawable), index, index + chip.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.setSpan(new ChipClickSpan(callback), index, index + chip.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return index + chip.length() + 1;
}
 
Example 35
Project: ForPDA   File: Html.java   Source Code and License 6 votes vote down vote up
private static void startImg(Editable text, Attributes attributes, Html.ImageGetter img) {
    String src = attributes.getValue("", "src");
    Drawable d = null;
    if (img != null) {
        d = img.getDrawable(src);
    }
    if (d == null) {
        //TODO kakayato tam drawabla hz zachem
        /*d = Resources.getSystem().
                getDrawable(R.drawable.adf);*/
        d = App.getContext().getResources().getDrawable(R.drawable.adf);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    }
    int len = text.length();
    text.append("\uFFFC");
    text.setSpan(new ImageSpan(d, src), len, text.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
 
Example 36
Project: yun2win-sdk-android   File: IncomingMsgPrompt.java   Source Code and License 6 votes vote down vote up
public void show(MessageModel newMessage) {
    if (newMessageTipLayout == null) {
        init();
    }
    if (!TextUtils.isEmpty(newMessage.getEntity().getSender())) {
        newMessageTipHeadImageView.loadBuddyAvatarbyuid(newMessage.getEntity().getSender(), R.drawable.circle_image_transparent);
    } else {
        newMessageTipHeadImageView.resetImageView();
    }

    MoonUtil.identifyFaceExpression(context, newMessageTipTextView, newMessage.getEntity().getContent(),
            ImageSpan.ALIGN_BOTTOM);
    newMessageTipLayout.setVisibility(View.VISIBLE);
    uiHandler.removeCallbacks(showNewMessageTipLayoutRunnable);
    uiHandler.postDelayed(showNewMessageTipLayoutRunnable, 5 * 1000);
}
 
Example 37
Project: yun2win-sdk-android   File: MoonUtil.java   Source Code and License 6 votes vote down vote up
private static SpannableString replaceEmoticons(Context context, String value, float scale, int align) {
	if(TextUtils.isEmpty(value)) {
		value="";
	}
	
	SpannableString mSpannableString = new SpannableString(value);
	Matcher matcher = EmojiManager.getPattern().matcher(value);
	while (matcher.find()) {
		int start = matcher.start();
		int end = matcher.end();
		String emot = value.substring(start, end);
		Drawable d = getEmotDrawable(context, emot, scale);
		if (d != null) {
			ImageSpan span = new ImageSpan(d, align);
			mSpannableString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
	return mSpannableString;
}
 
Example 38
Project: yun2win-sdk-android   File: MoonUtil.java   Source Code and License 6 votes vote down vote up
public static void replaceEmoticons(Context context, Editable editable, int start, int count) {
	if (count <= 0 || editable.length() < start + count) 
		return;
	
	CharSequence s = editable.subSequence(start, start + count);
	Matcher matcher = EmojiManager.getPattern().matcher(s);
	while (matcher.find()) {
		int from = start + matcher.start();
		int to = start + matcher.end();
		String emot = editable.subSequence(from, to).toString();
		Drawable d = getEmotDrawable(context, emot, SMALL_SCALE);
		if (d != null) {
			ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
			editable.setSpan(span, from, to, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
}
 
Example 39
Project: monolog-android   File: EaseSmileUtils.java   Source Code and License 6 votes vote down vote up
/**
 * replace existing spannable with smiles
 * @param context
 * @param spannable
 * @return
 */
public static boolean addSmiles(Context context, Spannable spannable) {
    boolean hasChanges = false;
    for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
        Matcher matcher = entry.getKey().matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            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 {
                    set = false;
                    break;
                }
            if (set) {
                hasChanges = true;
                spannable.setSpan(new ImageSpan(context, entry.getValue()),
                        matcher.start(), matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
    return hasChanges;
}
 
Example 40
Project: youkes_vr   File: ExpressionUtil.java   Source Code and License 6 votes vote down vote up
public static SpannableStringBuilder parse(Context mContext, String content, int itemWidth, int itemHeight) {
	SpannableStringBuilder sb = new SpannableStringBuilder(content);
	String regex = "\\[[^\\]]+\\]";//[图片]

	Pattern p = Pattern.compile(regex);
	Matcher m = p.matcher(content);
	while (m.find()) {

		String tempText = m.group();
		if (tempText.equals("[图片]")) {
			continue;
		}

		String png = tempText.substring("[".length(), tempText.length() - "]".length());
		try {

			ImageSpan ispan = new ImageSpan(mContext, BitmapFactory.decodeStream(mContext.getAssets().open(png)));
			ispan.getDrawable().setBounds(0, 0, itemWidth, itemHeight);
			sb.setSpan(ispan, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

	}
	return sb;
}
 
Example 41
Project: aptoide-client-v8   File: InstallWarningDialog.java   Source Code and License 6 votes vote down vote up
private void setTextBadges(View contentView) {
  // We need a placeholder for the span image in order to avoid it from disappearing in case
  // it is the last character in the line. It happens in when device orientation changes.
  final String placeholder = "[placeholder]";
  final String stringTextTemp = contentView.getContext()
      .getString(R.string.dialog_install_warning_credibility_text, placeholder);
  final String stringText = stringTextTemp.replaceFirst("Aptoide", marketName);
  final SpannableString text = new SpannableString(stringText);

  final int placeholderIndex = stringText.indexOf(placeholder);
  final ImageSpan trustedBadge =
      new ImageSpan(contentView.getContext(), R.drawable.ic_badge_trusted);

  text.setSpan(trustedBadge, placeholderIndex, placeholderIndex + placeholder.length(),
      Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  ((TextView) contentView.findViewById(R.id.dialog_install_warning_credibility_text)).setText(
      text);
}
 
Example 42
Project: TextSecure   File: Emoji.java   Source Code and License 6 votes vote down vote up
public SpannableString emojify(SpannableString text, double size, PageLoadedListener pageLoadedListener) {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) return text;

  Matcher matches = EMOJI_RANGE.matcher(text);

  while (matches.find()) {
    String resource = Integer.toHexString(matches.group().codePointAt(0));

    Drawable drawable = getEmojiDrawable(resource, size, pageLoadedListener);
    if (drawable != null) {
      ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
      text.setSpan(imageSpan, matches.start(), matches.end(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
  }

  return text;
}
 
Example 43
Project: S1-Next   File: TagHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Replaces {@link android.view.View.OnClickListener}
 * with {@link ImageClickableResizeSpan}.
 * <p>
 * See android.text.Html.HtmlToSpannedConverter#startImg(android.text.SpannableStringBuilder, org.xml.sax.Attributes, android.text.Html.ImageGetter)
 */
private void handleImg(boolean opening, Editable output) {
    if (!opening) {
        int end = output.length();

        // \uFFFC: OBJECT REPLACEMENT CHARACTER
        int len = "\uFFFC".length();
        ImageSpan imageSpan = output.getSpans(end - len, end, ImageSpan.class)[0];

        String url = imageSpan.getSource();
        if (url == null) {
            url = "";
        }
        // replace \uFFFC with ImageSpan's source
        // in order to support url copyFrom when selected
        output.replace(end - len, end, url);

        output.removeSpan(imageSpan);
        // make this ImageSpan clickable
        output.setSpan(new ImageClickableResizeSpan(imageSpan.getDrawable(), url, images),
                end - len, output.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example 44
Project: Amumu   File: ImageSpanTarget.java   Source Code and License 6 votes vote down vote up
@Override
public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
    TextView tv = textView.get();
    if (tv != null) {
        BitmapDrawable bitmapDrawable = new BitmapDrawable(tv.getResources(), bitmap);
        // image span doesn't handle scaling so we manually set bounds
        if (bitmap.getWidth() > tv.getWidth()) {
            float aspectRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth();
            bitmapDrawable.setBounds(0, 0, tv.getWidth(), (int) (aspectRatio * tv.getWidth()));
        } else {
            bitmapDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
        }
        ImageSpan span = new ImageSpan(bitmapDrawable);
        // add the image span and remove our marker
        SpannableStringBuilder ssb = new SpannableStringBuilder(tv.getText());
        int start = ssb.getSpanStart(loadingSpan);
        int end = ssb.getSpanEnd(loadingSpan);
        if (start >= 0 && end >= 0) {
            ssb.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        ssb.removeSpan(loadingSpan);
        // animate the change
        TransitionManager.beginDelayedTransition((ViewGroup) tv.getParent());
        tv.setText(ssb);
    }
}
 
Example 45
Project: QDNews   File: ABTextUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 替换文本为图片
 *
 * @param charSequence
 * @param regPattern
 * @param drawable
 * @return
 */
public static SpannableString replaceImageSpan(CharSequence charSequence, String regPattern, Drawable drawable) {
    SpannableString ss = charSequence instanceof SpannableString ? (SpannableString) charSequence : new SpannableString(charSequence);
    try {
        ImageSpan is = new ImageSpan(drawable);
        Pattern pattern = Pattern.compile(regPattern);
        Matcher matcher = pattern.matcher(ss);
        while (matcher.find()) {
            String key = matcher.group();
            ss.setSpan(is, matcher.start(), matcher.start() + key.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }
    } catch (Exception ex) {
        Logger.e(TAG, ex);
    }

    return ss;
}
 
Example 46
Project: enjoychat   File: FaceTextUtils.java   Source Code and License 6 votes vote down vote up
/** 
  * toSpannableString
  * @return SpannableString
  * @throws
  */
public static SpannableString toSpannableString(Context context, String text) {
	if (!TextUtils.isEmpty(text)) {
		SpannableString spannableString = new SpannableString(text);
		int start = 0;
		Pattern pattern = Pattern.compile("\\\\ue[a-z0-9]{3}", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			String faceText = matcher.group();
			String key = faceText.substring(1);
			BitmapFactory.Options options = new BitmapFactory.Options();
			Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
					context.getResources().getIdentifier(key, "drawable", context.getPackageName()), options);
			ImageSpan imageSpan = new ImageSpan(context, bitmap);
			int startIndex = text.indexOf(faceText, start);
			int endIndex = startIndex + faceText.length();
			if (startIndex >= 0)
				spannableString.setSpan(imageSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			start = (endIndex - 1);
		}

		return spannableString;
	} else {
		return new SpannableString("");
	}
}
 
Example 47
Project: enjoychat   File: FaceTextUtils.java   Source Code and License 6 votes vote down vote up
public static SpannableString toSpannableString(Context context, String text, SpannableString spannableString) {

		int start = 0;
		Pattern pattern = Pattern.compile("\\\\ue[a-z0-9]{3}", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			String faceText = matcher.group();
			String key = faceText.substring(1);
			BitmapFactory.Options options = new BitmapFactory.Options();
//			options.inSampleSize = 2;
			Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), context.getResources()
					.getIdentifier(key, "drawable", context.getPackageName()), options);
			ImageSpan imageSpan = new ImageSpan(context, bitmap);
			int startIndex = text.indexOf(faceText, start);
			int endIndex = startIndex + faceText.length();
			if (startIndex >= 0)
				spannableString.setSpan(imageSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			start = (endIndex - 1);
		}

		return spannableString;
	}
 
Example 48
Project: QQ   File: EmoticonsEditText.java   Source Code and License 6 votes vote down vote up
private CharSequence replace(String text) {
	try {
		SpannableString spannableString = new SpannableString(text);
		int start = 0;
		Pattern pattern = buildPattern();
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			String faceText = matcher.group();
			String key = faceText.substring(1);
			BitmapFactory.Options options = new BitmapFactory.Options();
			Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(),
					getContext().getResources().getIdentifier(key, "drawable", getContext().getPackageName()), options);
			ImageSpan imageSpan = new ImageSpan(getContext(), bitmap);
			int startIndex = text.indexOf(faceText, start);
			int endIndex = startIndex + faceText.length();
			if (startIndex >= 0)
				spannableString.setSpan(imageSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			start = (endIndex - 1);
		}
		return spannableString;
	} catch (Exception e) {
		return text;
	}
}
 
Example 49
Project: RichEditText   File: RichEditText.java   Source Code and License 6 votes vote down vote up
/**
 * use local uri to insert a image
 *
 * @param uri image uri
 */
public void insertImage(Uri uri) {
    String path = UriUtils.getValidPath(getContext(), uri);
    Bitmap bitmap = bitmapCreator.getBitmapByDiskPath(path);

    SpannableString ss = new SpannableString(path);

    //construct a Drawable and set Bounds
    Drawable mDrawable = new BitmapDrawable(getContext().getResources(), bitmap);
    int width = mDrawable.getIntrinsicWidth();
    int height = mDrawable.getIntrinsicHeight();
    mDrawable.setBounds(0, 0, width > 0 ? width : 0, height > 0 ? height : 0);

    ImageSpan span = new ImageSpan(mDrawable, path, DynamicDrawableSpan.ALIGN_BOTTOM);
    ss.setSpan(span, 0, path.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    int start = this.getSelectionStart();

    getEditableText().insert(start, ss);//insert the imageSpan
    setSelection(start + ss.length());  //set selection start position
}
 
Example 50
Project: RichEditText   File: HtmlToSpannedConverter.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation")
private static void startImg(SpannableStringBuilder text,
                             Attributes attributes, Html.ImageGetter img)
{
    String src = attributes.getValue("", "src");
    Drawable d = null;
    if (img != null) {
        d = img.getDrawable(src);
    }
    if (d == null) {
        d = Resources.getSystem().getDrawable(R.drawable.unknown_image);
        if (d == null) {
            return;
        }
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    }
    int len = text.length();
    text.append("\uFFFC");

    text.setSpan(new ImageSpan(d, src), len, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
 
Example 51
Project: GitHub   File: Spanny.java   Source Code and License 5 votes vote down vote up
/**
 * Add the ImageSpan to the start of the text.
 * @return this {@code Spanny}.
 */
public Spanny append(CharSequence text, ImageSpan imageSpan) {
    text = "." + text;
    append(text);
    setSpan(imageSpan, length() - text.length(), length() - text.length() + 1);
    return this;
}
 
Example 52
Project: EmotionApp   File: SpanStringUtils.java   Source Code and License 5 votes vote down vote up
public static SpannableString getEmotionContent(int emotion_map_type, final Context context, final TextView tv, String source) {
        SpannableString spannableString = new SpannableString(source);
        Resources res = context.getResources();

        String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]";
        Pattern patternEmotion = Pattern.compile(regexEmotion);
        Matcher matcherEmotion = patternEmotion.matcher(spannableString);

        while (matcherEmotion.find()) {
            // 获取匹配到的具体字符
            String key = matcherEmotion.group();
            // 匹配字符串的开始位置
            int start = matcherEmotion.start();
            // 利用表情名字获取到对应的图片
            Integer imgRes = EmotionUtils.getImgByName(emotion_map_type, key);
            if (imgRes != -1) {//-1代表纯文本,没有图片
                // 压缩表情图片
                int size = (int) tv.getTextSize() * 13 / 10;
                Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);

//				ImageSpan span = new ImageSpan(context, scaleBitmap);
                final CenterAlignImageSpan span = new CenterAlignImageSpan(context, scaleBitmap, ImageSpan.ALIGN_BASELINE);
                spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return spannableString;
    }
 
Example 53
Project: ceji_android   File: ScrollingStrategy.java   Source Code and License 5 votes vote down vote up
private Spannable addEndTag(SpannableStringBuilder builder) {
	
	//Don't add the tag to the last section.
	Spine spine = bookView.getSpine();
	
	if (spine == null || spine.getPosition() >= spine.size() -1 ) {
		return builder;
	}
	
	int length = builder.length();
	builder.append("\uFFFC");
	builder.append("\n");
	builder.append( context.getString(R.string.end_of_section));
	//If not, consider it an internal nav link.			
	ClickableSpan span = new ClickableSpan() {
			
		@Override
		public void onClick(View widget) {
			pageDown();					
		}
	};

	Drawable img = context.getResources().getDrawable(R.drawable.gateway);
	img.setBounds(0, 0, img.getIntrinsicWidth(), img.getIntrinsicHeight() );
	builder.setSpan(new ImageSpan(img), length, length+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	builder.setSpan(span, length, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

       builder.setSpan( (AlignmentSpan) () -> Alignment.ALIGN_CENTER
		, length, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

	return builder;		
}
 
Example 54
Project: MyFire   File: FavortListAdapter.java   Source Code and License 5 votes vote down vote up
private SpannableString setImageSpan(){
    String text = "  ";
    SpannableString imgSpanText = new SpannableString(text);
    imgSpanText.setSpan(new ImageSpan(AppApplication.getAppContext(), R.drawable.dianzansmal, DynamicDrawableSpan.ALIGN_BASELINE),
            0 , 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return imgSpanText;
}
 
Example 55
Project: airgram   File: ChannelCreateActivity.java   Source Code and License 5 votes vote down vote up
private ChipSpan createAndPutChipForUser(TLRPC.User user) {
    try {
        LayoutInflater lf = (LayoutInflater) ApplicationLoader.applicationContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View textView = lf.inflate(R.layout.group_create_bubble, null);
        TextView text = (TextView)textView.findViewById(R.id.bubble_text_view);
        String name = UserObject.getUserName(user);
        if (name.length() == 0 && user.phone != null && user.phone.length() != 0) {
            name = PhoneFormat.getInstance().format("+" + user.phone);
        }
        text.setText(name + ", ");

        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        textView.measure(spec, spec);
        textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
        Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(b);
        canvas.translate(-textView.getScrollX(), -textView.getScrollY());
        textView.draw(canvas);
        textView.setDrawingCacheEnabled(true);
        Bitmap cacheBmp = textView.getDrawingCache();
        Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
        textView.destroyDrawingCache();

        final BitmapDrawable bmpDrawable = new BitmapDrawable(b);
        bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight());

        SpannableStringBuilder ssb = new SpannableStringBuilder("");
        ChipSpan span = new ChipSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE);
        allSpans.add(span);
        selectedContacts.put(user.id, span);
        for (ImageSpan sp : allSpans) {
            ssb.append("<<");
            ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        nameTextView.setText(ssb);
        nameTextView.setSelection(ssb.length());
        return span;
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    return null;
}
 
Example 56
Project: CSipSimple   File: SmileyParser.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 57
Project: CSipSimple   File: SearchView.java   Source Code and License 5 votes vote down vote up
private CharSequence getDecoratedHint(CharSequence hintText) {
    // If the field is always expanded, then don't add the search icon to the hint
    if (!mIconifiedByDefault) return hintText;

    SpannableStringBuilder ssb = new SpannableStringBuilder("   "); // for the icon
    ssb.append(hintText);
    Drawable searchIcon = getContext().getResources().getDrawable(getSearchIconId());
    int textSize = (int) (mQueryTextView.getTextSize() * 1.25);
    searchIcon.setBounds(0, 0, textSize, textSize);
    ssb.setSpan(new ImageSpan(searchIcon), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ssb;
}
 
Example 58
Project: TestChat   File: LikerTextView.java   Source Code and License 5 votes vote down vote up
private SpannableString setImageSpan(List<String> list) {
        SpannableString spannableString = new SpannableString("..");
        if (list != null && list.contains(UserManager.getInstance().getCurrentUser().getObjectId())) {
                spannableString.setSpan(new ImageSpan(getContext(), R.drawable.ic_favorite_deep_orange_a700_24dp, DynamicDrawableSpan.ALIGN_BASELINE), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
                spannableString.setSpan(new ImageSpan(getContext(), R.drawable.ic_favorite_border_deep_orange_a700_24dp, DynamicDrawableSpan.ALIGN_BASELINE), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
}
 
Example 59
Project: Hitalk   File: PraiseListView.java   Source Code and License 5 votes vote down vote up
private SpannableString setImageSpan(){
    String text = "  ";
    SpannableString imgSpanText = new SpannableString(text);
    imgSpanText.setSpan(new ImageSpan(HiTalkApplication.mAppContext, R.drawable.icon_praise, DynamicDrawableSpan.ALIGN_BASELINE),
            0 , 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return imgSpanText;
}
 
Example 60
Project: Hitalk   File: SmileUtils.java   Source Code and License 5 votes vote down vote up
/**
 * replace existing spannable with smiles
 * @param context
 * @param spannable
 * @return
 */
public static boolean addSmiles(Context context, Spannable spannable) {
    boolean hasChanges = false;
    for (Entry<Pattern, Object> entry : emoticons.entrySet()) {
        Matcher matcher = entry.getKey().matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            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 {
                    set = false;
                    break;
                }
            if (set) {
                hasChanges = true;
                Object value = entry.getValue();
                if(value instanceof String && !((String) value).startsWith("http")){
                    File file = new File((String) value);
                    if(!file.exists() || file.isDirectory()){
                        return false;
                    }
                    spannable.setSpan(new ImageSpan(context, Uri.fromFile(file)),
                            matcher.start(), matcher.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }else{
                    spannable.setSpan(new ImageSpan(context, (Integer)value),
                            matcher.start(), matcher.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }
    }
    
    return hasChanges;
}