Example usage for android.text.style ImageSpan ImageSpan

List of usage examples for android.text.style ImageSpan ImageSpan

Introduction

In this page you can find the example usage for android.text.style ImageSpan ImageSpan.

Prototype

public ImageSpan(@NonNull Context context, @DrawableRes int resourceId) 

Source Link

Document

Constructs an ImageSpan from a Context and a resource id with the default alignment DynamicDrawableSpan#ALIGN_BOTTOM

Usage

From source file:Main.java

/**
 * replace existing spannable with smiles
 * /*from   w  w w . j a  v  a2 s. c o m*/
 * @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;
}

From source file:Main.java

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);//from  w  w  w .  ja v a 2 s . co  m
    }

    return spannableString;
}

From source file:Main.java

/**
 * replace existing spannable with smiles
 * @param context/* w  w w .ja v a  2s  . c  o m*/
 * @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;
}

From source file:io.spw.hello.SectionsPagerAdapter.java

@Override
public CharSequence getPageTitle(int position) {
    Drawable image = mActivity.getResources().getDrawable(imageResIdUnselected[position]);

    int currentPosition = ((MainActivity) mActivity).mViewPager.getCurrentItem();

    if (position == currentPosition) {
        image = mActivity.getResources().getDrawable(imageResIdSelected[position]);
    }//from w  ww. ja  va  2s .  c  om

    image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicWidth());
    SpannableString ss = new SpannableString(" ");
    ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
    ss.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ss;

}

From source file:xyz.getgoing.going.MainPagerAdapter.java

/** Fills action bar with icons */
@Override/*  w  w  w  .  j  av  a 2 s.c  om*/
public CharSequence getPageTitle(int position) {
    Drawable image = mMainActivity.getResources().getDrawable(mImageResIdsUnselected[position]);

    if (position == mCurrentPosition) {
        image = mMainActivity.getResources().getDrawable(mImageResIdsSelected[position]);
    }

    image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicWidth());
    SpannableString ss = new SpannableString(" ");
    ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
    ss.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ss;

}

From source file:org.lytsing.android.weibo.ui.ComposeActivity.java

private void initGridView() {
    mGVFaceAdapter = new GridViewFaceAdapter(this);
    mGridView = (GridView) findViewById(R.id.tweet_pub_faces);
    mGridView.setAdapter(mGVFaceAdapter);
    mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // ?/*from w  w  w. j  a v  a  2s  . c o  m*/
            SpannableString ss = new SpannableString(view.getTag().toString());
            Drawable d = getResources().getDrawable((int) mGVFaceAdapter.getItemId(position));
            d.setBounds(0, 0, 35, 35);//?
            ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
            ss.setSpan(span, 0, view.getTag().toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // ?
            mEdit.getText().insert(mEdit.getSelectionStart(), ss);
        }
    });
}

From source file:com.vuze.android.remote.activity.LoginActivity.java

private void setupGuideText(TextView tvLoginGuide) {
    AndroidUtilsUI.linkify(tvLoginGuide);
    CharSequence text = tvLoginGuide.getText();

    SpannableStringBuilder ss = new SpannableStringBuilder(text);
    String string = text.toString();

    new SpanBubbles().setSpanBubbles(ss, string, "|", tvLoginGuide.getPaint(),
            AndroidUtilsUI.getStyleColor(this, R.attr.login_text_color),
            AndroidUtilsUI.getStyleColor(this, R.attr.login_textbubble_color),
            AndroidUtilsUI.getStyleColor(this, R.attr.login_text_color));

    int indexOf = string.indexOf("@@");
    if (indexOf >= 0) {
        int style = ImageSpan.ALIGN_BASELINE;
        int newHeight = tvLoginGuide.getBaseline();
        if (newHeight <= 0) {
            newHeight = tvLoginGuide.getLineHeight();
            style = ImageSpan.ALIGN_BOTTOM;
            if (newHeight <= 0) {
                newHeight = 20;/*  w ww.j  a v  a2 s  .co m*/
            }
        }
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.guide_icon);
        int oldWidth = drawable.getIntrinsicWidth();
        int oldHeight = drawable.getIntrinsicHeight();
        int newWidth = (oldHeight > 0) ? (oldWidth * newHeight) / oldHeight : newHeight;
        drawable.setBounds(0, 0, newWidth, newHeight);

        ImageSpan imageSpan = new ImageSpan(drawable, style);
        ss.setSpan(imageSpan, indexOf, indexOf + 2, 0);
    }

    tvLoginGuide.setText(ss);
}

From source file:com.vuze.android.remote.spanbubbles.SpanTags.java

public void setTagBubbles(final SpannableStringBuilder ss, String text, String token) {
    if (ss.length() > 0) {
        // hack to ensure descent is always added by TextView
        ss.append("\u200B");
    }// w ww  . ja  v a2  s  .  c  o  m

    if (tvTags == null) {
        Log.e(TAG, "no tvTags");
        return;
    }

    TextPaint p = tvTags.getPaint();

    // Start and end refer to the points where the span will apply
    int tokenLen = token.length();
    int base = 0;

    if (showIcon && tagDrawables == null) {
        createDrawTagables();
    }

    while (true) {
        int start = text.indexOf(token, base);
        int end = text.indexOf(token, start + tokenLen);

        if (start < 0 || end < 0) {
            break;
        }

        base = end + tokenLen;

        final int fSpanStart = start;
        final int fSpanEnd = end + tokenLen;

        String id = text.substring(start + tokenLen, end);

        Map mapTag = null;
        try {
            long tagUID = Long.parseLong(id);
            mapTag = sessionInfo.getTag(tagUID);
        } catch (Throwable ignore) {
        }

        final String word = MapUtils.getMapString(mapTag, "name", "" + id);
        final Map fMapTag = mapTag;

        final DrawableTag imgDrawable = new DrawableTag(context, p, word, showIcon ? tagDrawables : null,
                mapTag, drawCount) {

            @Override
            public boolean isTagPressed() {
                if (!AndroidUtils.usesNavigationControl()) {
                    return false;
                }
                int selectionEnd = tvTags.getSelectionEnd();
                if (selectionEnd < 0) {
                    return false;
                }
                int selectionStart = tvTags.getSelectionStart();
                return selectionStart == fSpanStart && selectionEnd == fSpanEnd;
            }

            @Override
            public int getTagState() {
                if (listener == null) {
                    return TAG_STATE_SELECTED;
                }
                return listener.getTagState(fMapTag, word);
            }
        };

        if (countFontRatio > 0) {
            imgDrawable.setCountFontRatio(countFontRatio);
        }

        imgDrawable.setBounds(0, 0, imgDrawable.getIntrinsicWidth(), imgDrawable.getIntrinsicHeight());
        //         Log.d(TAG, "State=" + Arrays.toString(imgDrawable.getState()));

        if (listener != null && showIcon) {
            int tagState = listener.getTagState(mapTag, word);
            int[] state = makeState(tagState, mapTag == null, false);
            imgDrawable.setState(state);
        }

        ImageSpan imageSpan = new ImageSpan(imgDrawable, DynamicDrawableSpan.ALIGN_BASELINE) {

            @Override
            public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
                int size = super.getSize(paint, text, start, end, fm);
                int width = -1;
                if (tvTags.getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) {
                    if (tvTags.getParent() instanceof ViewGroup) {
                        width = ((ViewGroup) tvTags.getParent()).getWidth();
                    }
                } else {
                    width = tvTags.getWidth();
                }
                if (width <= 0) {
                    return size;
                }
                return Math.min(size, width);
            }
        };

        ss.setSpan(imageSpan, start, end + tokenLen, 0);

        if (listener != null) {
            ClickableSpan clickSpan = new ClickableSpan() {

                @Override
                public void onClick(View widget) {
                    listener.tagClicked(fMapTag, word);

                    if (AndroidUtils.hasTouchScreen()) {
                        Selection.removeSelection((Spannable) tvTags.getText());
                    }
                    widget.invalidate();
                }
            };

            ss.setSpan(clickSpan, start, end + tokenLen, 0);
        }

    }
}

From source file:org.awesomeapp.messenger.ui.GalleryListItem.java

private SpannableString formatTimeStamp(Date date, int messageType, DateFormat format,
        GalleryListItem.DeliveryState delivery, EncryptionState encryptionState) {

    StringBuilder deliveryText = new StringBuilder();
    deliveryText.append(format.format(date));
    deliveryText.append(' ');

    if (delivery != null) {
        //this is for delivery
        if (delivery == DeliveryState.DELIVERED) {

            deliveryText.append(DELIVERED_SUCCESS);

        } else if (delivery == DeliveryState.UNDELIVERED) {

            deliveryText.append(DELIVERED_FAIL);
        }//from  w  w  w .  j av a2  s .  co  m
    }

    if (messageType != Imps.MessageType.POSTPONED)
        deliveryText.append(DELIVERED_SUCCESS);//this is for sent, so we know show 2 checks like WhatsApp!

    SpannableString spanText = null;

    if (encryptionState == EncryptionState.ENCRYPTED) {
        deliveryText.append('X');
        spanText = new SpannableString(deliveryText.toString());
        int len = spanText.length();

        spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_lock_outline_black_18dp), len - 1, len,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    } else if (encryptionState == EncryptionState.ENCRYPTED_AND_VERIFIED) {
        deliveryText.append('X');
        spanText = new SpannableString(deliveryText.toString());
        int len = spanText.length();

        spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_lock_outline_black_18dp), len - 1, len,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    } else {
        spanText = new SpannableString(deliveryText.toString());
        int len = spanText.length();

    }

    //   spanText.setSpan(new StyleSpan(Typeface.SANS_SERIF), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // spanText.setSpan(new RelativeSizeSpan(0.8f), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    //    spanText.setSpan(new ForegroundColorSpan(R.color.soft_grey),
    //        0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spanText;
}

From source file:cn.zhangls.android.weibo.utils.TextUtil.java

/**
 * ?? emoji /*www.  jav a 2  s  .c  o  m*/
 *
 * @param context   
 * @param builder   SpannableStringBuilder
 * @param arrayList ??
 */
private static void replaceEmoji(Context context, SpannableStringBuilder builder,
        ArrayList<StrHolder> arrayList, int textSze) {
    if (arrayList != null && arrayList.size() > 0) {
        PinyinUtil pinyinUtils = PinyinUtil.getInstance(context);
        for (StrHolder emoji : arrayList) {
            if (!emoji.getName().isEmpty()) {
                // ??? [] ?? [erha]
                if (emoji.getName().length() <= 2) {
                    return;
                }
                String substring = emoji.getName().substring(1, emoji.getName().length() - 1);
                String pinyin = pinyinUtils.getPinyin(substring);
                Log.d("emoji", "replaceEmoji: ======" + substring + "======" + pinyin);
                if (getResId(pinyin, R.drawable.class) != -1) {
                    //????Id
                    Drawable drawable = ContextCompat.getDrawable(context, getResId(pinyin, R.drawable.class));
                    drawable.setBounds(0, 0, textSze, textSze);
                    //??ImageSpan
                    ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                    // ??23????startend
                    // ???,[5,12)5125?12
                    builder.setSpan(imageSpan, emoji.getStart(), emoji.getEnd(),
                            Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                }
            }
        }
    }
}