Java Code Examples for android.text.SpannableString#setSpan()

The following examples show how to use android.text.SpannableString#setSpan() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EmoticonsEditText.java    From Conquer with Apache License 2.0 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 2
Source File: Methods.java    From DeviceInfo with Apache License 2.0 6 votes vote down vote up
/**
     * Set string with spannable.
     */
    public static SpannableStringBuilder getSpannablePriceTotalText(Context context, String text, String fontPath, boolean setFontBigger) {

        String[] result = text.split("=");
        String first = result[0];
        String second = result[1];
        first = first.concat("=");

//        Typeface font = Typeface.createFromAsset(context.getAssets(), fontPath);

        SpannableStringBuilder builder = new SpannableStringBuilder();

        SpannableString dkgraySpannable = new SpannableString(first + "");
        builder.append(dkgraySpannable);

        SpannableString blackSpannable = new SpannableString(second);
        if (setFontBigger) {
            blackSpannable.setSpan(new RelativeSizeSpan(1.3f), 0, second.length(), 0); // set size
        }
//        blackSpannable.setSpan(new CustomTypefaceSpan("", font), 0, second.length(), 0); // font weight
        builder.append(blackSpannable);

        return builder;
    }
 
Example 3
Source File: Version1EditText.java    From arcusandroid with Apache License 2.0 6 votes vote down vote up
private void applySpacing() {

        if (this == null || this.originalText == null) return;

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < originalText.length(); i++) {
            builder.append(originalText.charAt(i));
            if (i + 1 < originalText.length()) {
                builder.append("\u00A0");
            }
        }
        SpannableString finalText = new SpannableString(builder.toString());

        if (builder.toString().length() > 1) {
            for (int i = 1; i < builder.toString().length(); i += 2) {
                finalText.setSpan(new ScaleXSpan((spacing + 1) / 10), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        super.setText(finalText, BufferType.SPANNABLE);
    }
 
Example 4
Source File: ForgetIphonePasswordFragment.java    From FimiX8-RE with MIT License 6 votes vote down vote up
private SpannableString getEmailVerficationSpannableString() {
    String str1 = this.mContext.getString(R.string.login_email_send_hint1);
    String str2 = this.mContext.getString(R.string.login_send_email_hint2);
    SpannableString spannableString = new SpannableString(str1 + str2);
    spannableString.setSpan(new ForegroundColorSpan(this.mContext.getResources().getColor(R.color.register_agreement)), 0, str1.length(), 33);
    spannableString.setSpan(new ForegroundColorSpan(this.mContext.getResources().getColor(R.color.register_agreement)), str1.length() + str2.length(), str1.length() + str2.length(), 33);
    spannableString.setSpan(new ClickableSpan() {
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(ForgetIphonePasswordFragment.this.getResources().getColor(R.color.register_agreement_click));
            ds.setUnderlineText(false);
        }

        public void onClick(View widget) {
        }
    }, str1.length(), str1.length() + str2.length(), 33);
    return spannableString;
}
 
Example 5
Source File: SignPostActivity.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 6 votes vote down vote up
private void initBodyText() {
    mBodyText = (EditText) findViewById(R.id.reply_body_edittext);
    mBodyText.setSelected(true);

    Intent intent = getIntent();
    String prefix = intent.getStringExtra("prefix");
    if (prefix != null) {
        if (prefix.startsWith("[quote][pid=")
                && prefix.endsWith("[/quote]\n")) {
            SpannableString spanString = new SpannableString(prefix);
            spanString.setSpan(new BackgroundColorSpan(-1513240), 0, prefix.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), prefix.indexOf("[b]Post by"),
                    prefix.indexOf("):[/b]") + 5,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mBodyText.append(spanString);
        } else {
            mBodyText.append(prefix);
        }
        mBodyText.setSelection(prefix.length());
    }
}
 
Example 6
Source File: AboutActivity.java    From ONE-Unofficial with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    setTitle(R.string.item_about);

    String s = getResources().getString(R.string.content_about);
    int start=s.indexOf("『");
    int end=s.indexOf("』")+1;
    SpannableString content = new SpannableString(s);
    //ClickableSpan会默认给区域内的文件设为下划线、绿色字体
    content.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=one.hh.oneclient"));
            startActivity(intent);
        }
    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    //此处将上面的绿色字体覆盖为了蓝色(前景色即为字体的颜色)
    content.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    textAbout.setText(content);
}
 
Example 7
Source File: MsgTextView.java    From Tok-Android with GNU General Public License v3.0 6 votes vote down vote up
public CharSequence buildOrderLink(CharSequence content) {
    String c = content.toString();
    SpannableString sp = new SpannableString(c);
    if (enableOrderLink) {
        Matcher orderMatcher = PatternUtil.getOrderMatcher(c);
        while (orderMatcher.find()) {
            sp.setSpan(new OrderLinkSpan(c.substring(orderMatcher.start(), orderMatcher.end())),
                orderMatcher.start(), orderMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    Matcher pkMatcher = PatternUtil.getPkMatcher(c);
    while (pkMatcher.find()) {
        sp.setSpan(new TokIdLinkSpan(c.substring(pkMatcher.start(), pkMatcher.end())),
            pkMatcher.start(), pkMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    setText(sp);
    setMovementMethod(LinkMovementMethod.getInstance());
    return sp;
}
 
Example 8
Source File: Trestle.java    From Trestle with Apache License 2.0 5 votes vote down vote up
private static void setUpQuoteSpan(Span span, SpannableString ss, int start, int end) {
    int quoteColor = span.getQuoteColor();
    if (quoteColor != 0) {
        ss.setSpan(
                new QuoteSpan(quoteColor),
                start,
                end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example 9
Source File: LeaderboardAdapter.java    From Leaderboards with Apache License 2.0 5 votes vote down vote up
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
    Row row = leaderboardData.get(i);

    int ranking = row.getRanking();
    if(ranking == 1) viewHolder.rank.setBackgroundResource(R.drawable.ranking_textview_background_gold);
    else if(ranking == 2) viewHolder.rank.setBackgroundResource(R.drawable.ranking_textview_background_silver);
    else if(ranking == 3) viewHolder.rank.setBackgroundResource(R.drawable.ranking_textview_background_bronze);
    else if(row.getFactionId() == 0) viewHolder.rank.setBackgroundResource(R.drawable.ranking_textview_background_alliance);
    else viewHolder.rank.setBackgroundResource(R.drawable.ranking_textview_background_horde);

    viewHolder.rank.setText(String.valueOf(ranking));
    viewHolder.name.setText(row.getName());
    viewHolder.name.setTextColor(classColors[row.getClassId() - 1]);
    viewHolder.realm.setText(row.getRealmName());
    viewHolder.rating.setText(String.valueOf(row.getRating()));

    String wins = String.valueOf(row.getSeasonWins());
    String losses = String.valueOf(row.getSeasonLosses());

    SpannableString span = new SpannableString(wins + "/" + losses);
    span.setSpan(new ForegroundColorSpan(context.getResources().
            getColor(R.color.wins)), 0, wins.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    span.setSpan(new ForegroundColorSpan(context.getResources().
            getColor(R.color.losses)), wins.length() + 1, span.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    viewHolder.season.setText(span);
    viewHolder.faction.setImageResource(row.getFactionId() == 0 ? R.drawable.ic_alliance : R.drawable.ic_horde);

    int raceId = row.getRaceId();
    viewHolder.race.setImageResource(row.getGenderId() == 0 ? Constants.MALE_RACES[raceId - 1] : Constants.FEMALE_RACES[raceId - 1]);
    viewHolder.spec.setImageResource(Constants.SPEC_CLASSES[row.getClassId() - 1]);
    viewHolder.itemPosition = i;
}
 
Example 10
Source File: ContactsFragment.java    From hashtag-view with MIT License 5 votes vote down vote up
private CharSequence getContactText() {
    SpannableString spannable = new SpannableString(getString(R.string.contact));
    spannable.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            IntentFactory.email(getActivity(), getString(R.string.email));
        }
    }, 8, 31, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return spannable;
}
 
Example 11
Source File: CustomHintContentHolder.java    From hintcase with Apache License 2.0 5 votes vote down vote up
private View getTextViewTitle(Context context) {
    LinearLayout.LayoutParams linearLayoutParamsTitle =
            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
    linearLayoutParamsTitle.setMargins(0, 0, 0, 20);
    TextView textViewTitle = new TextView(context);
    textViewTitle.setLayoutParams(linearLayoutParamsTitle);
    textViewTitle.setGravity(Gravity.CENTER_HORIZONTAL);
    SpannableString spannableStringTitle= new SpannableString(contentTitle);
    TextAppearanceSpan titleTextAppearanceSpan = new TextAppearanceSpan(context, titleStyleId);
    spannableStringTitle.setSpan(titleTextAppearanceSpan, 0, spannableStringTitle.length(), 0);
    textViewTitle.setText(spannableStringTitle);
    return textViewTitle;
}
 
Example 12
Source File: SnackBarUtil.java    From FastLib with Apache License 2.0 5 votes vote down vote up
/**
 * 显示SnackBar
 */
public void show() {
    final View view = mParent.get();
    if (view == null) {
        return;
    }
    if (mMessageColor != DEFAULT_COLOR) {
        SpannableString spannableString = new SpannableString(mMessage);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(mMessageColor);
        spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mWeakReference = new WeakReference<>(Snackbar.make(view, spannableString, mDuration));
    } else {
        mWeakReference = new WeakReference<>(Snackbar.make(view, mMessage, mDuration));
    }
    final Snackbar snackbar = mWeakReference.get();
    final View snackView = snackbar.getView();
    if (mBgResource != -1) {
        snackView.setBackgroundResource(mBgResource);
    } else if (mBgColor != DEFAULT_COLOR) {
        snackView.setBackgroundColor(mBgColor);
    }
    if (mBottomMargin != 0) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) snackView.getLayoutParams();
        params.bottomMargin = mBottomMargin;
    }
    if (mActionText.length() > 0 && mActionListener != null) {
        if (mActionTextColor != DEFAULT_COLOR) {
            snackbar.setActionTextColor(mActionTextColor);
        }
        snackbar.setAction(mActionText, mActionListener);
    }
    snackbar.show();
}
 
Example 13
Source File: ConsoleEditText.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
public CharSequence updateStr(CharSequence oldChars, int startPos, CharSequence newChars) {
    if (startPos < mLength) {
        return oldChars; //don't edit

    } else {//if (startPos >= mLength)
        SpannableString spannableString = new SpannableString(newChars);
        spannableString.setSpan(new ForegroundColorSpan(Color.GREEN), 0,
                spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }
}
 
Example 14
Source File: ConsoleEditText.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
public CharSequence insertStr(CharSequence newChars, int startPos) {
    if (startPos < mLength) { //it mean output from console
        return newChars;

    } else { //(startPos >= mLength)
        SpannableString spannableString = new SpannableString(newChars);
        spannableString.setSpan(new ForegroundColorSpan(Color.GREEN), 0,
                spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;

    }
}
 
Example 15
Source File: AbstractBarterLiActivity.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the Action bar title, using the desired {@link Typeface} loaded from {@link
 * TypefaceCache}
 *
 * @param title The title to set for the Action Bar
 */

public final void setActionBarTitle(final String title) {

    final SpannableString s = new SpannableString(title);
    s.setSpan(new TypefacedSpan(this, TypefaceCache.SLAB_REGULAR), 0, s.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Update the action bar title with the TypefaceSpan instance
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle(s);
}
 
Example 16
Source File: Link.java    From codeexamples-android with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.link);

    // text1 shows the android:autoLink property, which
    // automatically linkifies things like URLs and phone numbers
    // found in the text.  No java code is needed to make this
    // work.

    // text2 has links specified by putting <a> tags in the string
    // resource.  By default these links will appear but not
    // respond to user input.  To make them active, you need to
    // call setMovementMethod() on the TextView object.

    TextView t2 = (TextView) findViewById(R.id.text2);
    t2.setMovementMethod(LinkMovementMethod.getInstance());

    // text3 shows creating text with links from HTML in the Java
    // code, rather than from a string resource.  Note that for a
    // fixed string, using a (localizable) resource as shown above
    // is usually a better way to go; this example is intended to
    // illustrate how you might display text that came from a
    // dynamic source (eg, the network).

    TextView t3 = (TextView) findViewById(R.id.text3);
    t3.setText(
        Html.fromHtml(
            "<b>text3:</b>  Text with a " +
            "<a href=\"http://www.google.com\">link</a> " +
            "created in the Java source code using HTML."));
    t3.setMovementMethod(LinkMovementMethod.getInstance());

    // text4 illustrates constructing a styled string containing a
    // link without using HTML at all.  Again, for a fixed string
    // you should probably be using a string resource, not a
    // hardcoded value.

    SpannableString ss = new SpannableString(
        "text4: Click here to dial the phone.");

    ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 6,
               Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new URLSpan("tel:4155551212"), 13, 17,
               Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    TextView t4 = (TextView) findViewById(R.id.text4);
    t4.setText(ss);
    t4.setMovementMethod(LinkMovementMethod.getInstance());
}
 
Example 17
Source File: QiscusTextUtil.java    From qiscus-sdk-android with Apache License 2.0 4 votes vote down vote up
public static Spannable createQiscusSpannableText(
        String message,
        Map<String, QiscusRoomMember> members,
        @ColorInt int mentionAllColor, @ColorInt int mentionOtherColor,
        @ColorInt int mentionMeColor, MentionClickHandler mentionClickListener) {

    if (message == null) {
        return new SpannableString("");
    }

    QiscusAccount qiscusAccount = QiscusCore.getQiscusAccount();

    SpannableStringBuilder spannable = new SpannableStringBuilder();
    int length = message.length();
    int lastNotMention = 0;
    int startPosition = 0;
    boolean ongoing = false;
    for (int i = 0; i < length; i++) {
        if (!ongoing && i < length - 1 && message.charAt(i) == '@' && message.charAt(i + 1) == '[') {
            ongoing = true;
            startPosition = i;
        }

        if (ongoing && message.charAt(i) == ']') {
            String mentionedUserId = message.substring(startPosition + 2, i);
            QiscusRoomMember mentionedUser = members.get(mentionedUserId);
            if (mentionedUser != null) {
                SpannableString mention = new SpannableString("@" + mentionedUser.getUsername());
                mention.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        if (mentionClickListener != null) {
                            mentionClickListener.onMentionClick(mentionedUser);
                        }
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        if (mentionedUserId.equals("all")) {
                            ds.setColor(mentionAllColor);
                        } else if (mentionedUserId.equals(qiscusAccount.getEmail())) {
                            ds.setColor(mentionMeColor);
                        } else {
                            ds.setColor(mentionOtherColor);
                        }
                    }
                }, 0, mention.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                if (lastNotMention != startPosition) {
                    spannable.append(message.substring(lastNotMention, startPosition));
                }
                spannable.append(mention);
                lastNotMention = i + 1;
            }
            ongoing = false;
        }
    }
    if (lastNotMention < length) {
        spannable.append(message.substring(lastNotMention, length));
    }
    return spannable;
}
 
Example 18
Source File: InputLogic.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 4 votes vote down vote up
/**
 * Reverts a previous commit with auto-correction.
 *
 * This is triggered upon pressing backspace just after a commit with auto-correction.
 *
 * @param inputTransaction The transaction in progress.
 * @param settingsValues the current values of the settings.
 */
private void revertCommit(final InputTransaction inputTransaction,
        final SettingsValues settingsValues) {
    final CharSequence originallyTypedWord = mLastComposedWord.mTypedWord;
    final String originallyTypedWordString =
            originallyTypedWord != null ? originallyTypedWord.toString() : "";
    final CharSequence committedWord = mLastComposedWord.mCommittedWord;
    final String committedWordString = committedWord.toString();
    final int cancelLength = committedWord.length();
    final String separatorString = mLastComposedWord.mSeparatorString;
    // If our separator is a space, we won't actually commit it,
    // but set the space state to PHANTOM so that a space will be inserted
    // on the next keypress
    final boolean usePhantomSpace = separatorString.equals(Constants.STRING_SPACE);
    // We want java chars, not codepoints for the following.
    final int separatorLength = separatorString.length();
    // TODO: should we check our saved separator against the actual contents of the text view?
    final int deleteLength = cancelLength + separatorLength;
    if (DebugFlags.DEBUG_ENABLED) {
        if (mWordComposer.isComposingWord()) {
            throw new RuntimeException("revertCommit, but we are composing a word");
        }
        final CharSequence wordBeforeCursor =
                mConnection.getTextBeforeCursor(deleteLength, 0).subSequence(0, cancelLength);
        if (!TextUtils.equals(committedWord, wordBeforeCursor)) {
            throw new RuntimeException("revertCommit check failed: we thought we were "
                    + "reverting \"" + committedWord
                    + "\", but before the cursor we found \"" + wordBeforeCursor + "\"");
        }
    }
    mConnection.deleteTextBeforeCursor(deleteLength);
    if (!TextUtils.isEmpty(committedWord)) {
        unlearnWord(committedWordString, inputTransaction.mSettingsValues,
                Constants.EVENT_REVERT);
    }
    final String stringToCommit = originallyTypedWord +
            (usePhantomSpace ? "" : separatorString);
    final SpannableString textToCommit = new SpannableString(stringToCommit);
    if (committedWord instanceof SpannableString) {
        final SpannableString committedWordWithSuggestionSpans = (SpannableString)committedWord;
        final Object[] spans = committedWordWithSuggestionSpans.getSpans(0,
                committedWord.length(), Object.class);
        final int lastCharIndex = textToCommit.length() - 1;
        // We will collect all suggestions in the following array.
        final ArrayList<String> suggestions = new ArrayList<>();
        // First, add the committed word to the list of suggestions.
        suggestions.add(committedWordString);
        for (final Object span : spans) {
            // If this is a suggestion span, we check that the word is not the committed word.
            // That should mostly be the case.
            // Given this, we add it to the list of suggestions, otherwise we discard it.
            if (span instanceof SuggestionSpan) {
                final SuggestionSpan suggestionSpan = (SuggestionSpan)span;
                for (final String suggestion : suggestionSpan.getSuggestions()) {
                    if (!suggestion.equals(committedWordString)) {
                        suggestions.add(suggestion);
                    }
                }
            } else {
                // If this is not a suggestion span, we just add it as is.
                textToCommit.setSpan(span, 0 /* start */, lastCharIndex /* end */,
                        committedWordWithSuggestionSpans.getSpanFlags(span));
            }
        }
        // Add the suggestion list to the list of suggestions.
        textToCommit.setSpan(new SuggestionSpan(mLatinIME /* context */,
                inputTransaction.mSettingsValues.mLocale,
                suggestions.toArray(new String[suggestions.size()]), 0 /* flags */,
                null /* notificationTargetClass */),
                0 /* start */, lastCharIndex /* end */, 0 /* flags */);
    }

    if (inputTransaction.mSettingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces) {
        mConnection.commitText(textToCommit, 1);
        if (usePhantomSpace) {
            mSpaceState = SpaceState.PHANTOM;
        }
    } else {
        // For languages without spaces, we revert the typed string but the cursor is flush
        // with the typed word, so we need to resume suggestions right away.
        final int[] codePoints = StringUtils.toCodePointArray(stringToCommit);
        mWordComposer.setComposingWord(codePoints,
                mLatinIME.getCoordinatesForCurrentKeyboard(codePoints));
        setComposingTextInternal(textToCommit, 1);
    }
    // Don't restart suggestion yet. We'll restart if the user deletes the separator.
    mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;

    // We have a separator between the word and the cursor: we should show predictions.
    inputTransaction.setRequiresUpdateSuggestions();
}
 
Example 19
Source File: SnackbarUtils.java    From AndroidUtilCode with Apache License 2.0 4 votes vote down vote up
/**
 * Show the snackbar.
 *
 * @param isShowTop True to show the snack bar on the top, false otherwise.
 */
public Snackbar show(boolean isShowTop) {
    View view = this.view;
    if (view == null) return null;
    if (isShowTop) {
        ViewGroup suitableParent = findSuitableParentCopyFromSnackbar(view);
        View topSnackBarContainer = suitableParent.findViewWithTag("topSnackBarCoordinatorLayout");
        if (topSnackBarContainer == null) {
            CoordinatorLayout topSnackBarCoordinatorLayout = new CoordinatorLayout(view.getContext());
            topSnackBarCoordinatorLayout.setTag("topSnackBarCoordinatorLayout");
            topSnackBarCoordinatorLayout.setRotation(180);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // bring to front
                topSnackBarCoordinatorLayout.setElevation(100);
            }
            suitableParent.addView(topSnackBarCoordinatorLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            topSnackBarContainer = topSnackBarCoordinatorLayout;
        }
        view = topSnackBarContainer;
    }
    if (messageColor != COLOR_DEFAULT) {
        SpannableString spannableString = new SpannableString(message);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(messageColor);
        spannableString.setSpan(
                colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        sReference = new WeakReference<>(Snackbar.make(view, spannableString, duration));
    } else {
        sReference = new WeakReference<>(Snackbar.make(view, message, duration));
    }
    final Snackbar snackbar = sReference.get();
    final Snackbar.SnackbarLayout snackbarView = (Snackbar.SnackbarLayout) snackbar.getView();
    if (isShowTop) {
        for (int i = 0; i < snackbarView.getChildCount(); i++) {
            View child = snackbarView.getChildAt(i);
            child.setRotation(180);
        }
    }
    if (bgResource != -1) {
        snackbarView.setBackgroundResource(bgResource);
    } else if (bgColor != COLOR_DEFAULT) {
        snackbarView.setBackgroundColor(bgColor);
    }
    if (bottomMargin != 0) {
        ViewGroup.MarginLayoutParams params =
                (ViewGroup.MarginLayoutParams) snackbarView.getLayoutParams();
        params.bottomMargin = bottomMargin;
    }
    if (actionText.length() > 0 && actionListener != null) {
        if (actionTextColor != COLOR_DEFAULT) {
            snackbar.setActionTextColor(actionTextColor);
        }
        snackbar.setAction(actionText, actionListener);
    }
    snackbar.show();
    return snackbar;
}
 
Example 20
Source File: CommonUtils.java    From SmartChart with Apache License 2.0 3 votes vote down vote up
/**
 * 转化不同大小颜色字体
 *
 * @param start
 * @param end
 * @param size
 * @param color
 * @param isChangeSize
 * @param isChanegColor
 * @param content
 * @param context
 * @return
 */
public static SpannableString setTextStyle(int start, int end, int size, int color, boolean isChangeSize, boolean isChanegColor, String content, Context context) {
    SpannableString ss = new SpannableString(content);
    if (isChangeSize) {
        ss.setSpan(new AbsoluteSizeSpan(DisplayUtil.dp2px(context, size)), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    if (isChanegColor) {
        ss.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    return ss;
}