Example usage for android.text SpannableStringBuilder setSpan

List of usage examples for android.text SpannableStringBuilder setSpan

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder setSpan.

Prototype

public void setSpan(Object what, int start, int end, int flags) 

Source Link

Document

Mark the specified range of text with the specified object.

Usage

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static SpannableStringBuilder replaceTags(String str, int flag) {
    try {//from w w w. j  a  v a 2s .com
        int start;
        int end;
        StringBuilder stringBuilder = new StringBuilder(str);
        if ((flag & FLAG_TAG_BR) != 0) {
            while ((start = stringBuilder.indexOf("<br>")) != -1) {
                stringBuilder.replace(start, start + 4, "\n");
            }
            while ((start = stringBuilder.indexOf("<br/>")) != -1) {
                stringBuilder.replace(start, start + 5, "\n");
            }
        }
        ArrayList<Integer> bolds = new ArrayList<>();
        if ((flag & FLAG_TAG_BOLD) != 0) {
            while ((start = stringBuilder.indexOf("<b>")) != -1) {
                stringBuilder.replace(start, start + 3, "");
                end = stringBuilder.indexOf("</b>");
                if (end == -1) {
                    end = stringBuilder.indexOf("<b>");
                }
                stringBuilder.replace(end, end + 4, "");
                bolds.add(start);
                bolds.add(end);
            }
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
        for (int a = 0; a < bolds.size() / 2; a++) {
            spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                    bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableStringBuilder;
    } catch (Exception e) {
        FileLog.e(e);
    }
    return new SpannableStringBuilder(str);
}

From source file:org.matrix.console.fragments.ConsoleMessageListFragment.java

public void onReadReceiptClick(String eventId, String userId, ReceiptData receipt) {
    RoomMember member = mRoom.getMember(userId);

    // sanity check
    if (null != member) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        SpannableStringBuilder body = new SpannableStringBuilder(getActivity().getString(R.string.read_receipt)
                + " : " + dateFormat.format(new Date(receipt.originServerTs)));
        body.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), 0,
                getActivity().getString(R.string.read_receipt).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        new AlertDialog.Builder(ConsoleApplication.getCurrentActivity()).setTitle(member.getName())
                .setMessage(body).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override//from  w  w  w .j a  v  a  2  s .  c om
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
    }
}

From source file:com.fa.mastodon.activity.MainActivity.java

private void setupSearchView() {
    searchView.attachNavigationDrawerToMenuButton(drawer.getDrawerLayout());

    // Setup content descriptions for the different elements in the search view.
    final View leftAction = searchView.findViewById(R.id.left_action);
    leftAction.setContentDescription(getString(R.string.action_open_drawer));
    searchView.setOnFocusChangeListener(new FloatingSearchView.OnFocusChangeListener() {
        @Override//from  w  w  w . j av  a2 s. c o m
        public void onFocus() {
            leftAction.setContentDescription(getString(R.string.action_close));
        }

        @Override
        public void onFocusCleared() {
            leftAction.setContentDescription(getString(R.string.action_open_drawer));
        }
    });
    View clearButton = searchView.findViewById(R.id.clear_btn);
    clearButton.setContentDescription(getString(R.string.action_clear));

    searchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
        @Override
        public void onSearchTextChanged(String oldQuery, String newQuery) {
            if (!oldQuery.equals("") && newQuery.equals("")) {
                searchView.clearSuggestions();
                return;
            }

            if (newQuery.length() < 3) {
                return;
            }

            searchView.showProgress();

            mastodonAPI.searchAccounts(newQuery, false, 5).enqueue(new Callback<List<Account>>() {
                @Override
                public void onResponse(Call<List<Account>> call, Response<List<Account>> response) {
                    if (response.isSuccessful()) {
                        searchView.swapSuggestions(response.body());
                        searchView.hideProgress();
                    } else {
                        searchView.hideProgress();
                    }
                }

                @Override
                public void onFailure(Call<List<Account>> call, Throwable t) {
                    searchView.hideProgress();
                }
            });
        }
    });

    searchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
        @Override
        public void onSuggestionClicked(SearchSuggestion searchSuggestion) {
            Account accountSuggestion = (Account) searchSuggestion;
            Intent intent = new Intent(MainActivity.this, AccountActivity.class);
            intent.putExtra("id", accountSuggestion.id);
            startActivity(intent);
        }

        @Override
        public void onSearchAction(String currentQuery) {
        }
    });

    searchView.setOnBindSuggestionCallback(new SearchSuggestionsAdapter.OnBindSuggestionCallback() {
        @Override
        public void onBindSuggestion(View suggestionView, ImageView leftIcon, TextView textView,
                SearchSuggestion item, int itemPosition) {
            Account accountSuggestion = ((Account) item);

            Picasso.with(MainActivity.this).load(accountSuggestion.avatar)
                    .placeholder(R.drawable.avatar_default).into(leftIcon);

            String searchStr = accountSuggestion.getDisplayName() + " " + accountSuggestion.username;
            final SpannableStringBuilder str = new SpannableStringBuilder(searchStr);

            str.setSpan(new StyleSpan(Typeface.BOLD), 0, accountSuggestion.getDisplayName().length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(str);
            textView.setMaxLines(1);
            textView.setEllipsize(TextUtils.TruncateAt.END);
        }
    });

    if (PreferenceManager.getDefaultSharedPreferences(this).getString("theme_selection", "light")
            .equals("black")) {
        searchView.setBackgroundColor(Color.parseColor("#444444"));
    }

}

From source file:org.catrobat.catroid.ui.MainMenuActivity.java

private void setMainMenuButtonContinueText() {
    Button mainMenuButtonContinue = (Button) this.findViewById(R.id.main_menu_button_continue);
    TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan(this, R.style.MainMenuButtonTextSecondLine);
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
    String mainMenuContinue = this.getString(R.string.main_menu_continue);

    spannableStringBuilder.append(mainMenuContinue);
    spannableStringBuilder.append("\n");
    spannableStringBuilder.append(Utils.getCurrentProjectName(this));

    spannableStringBuilder.setSpan(textAppearanceSpan, mainMenuContinue.length() + 1,
            spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

    mainMenuButtonContinue.setText(spannableStringBuilder);
}

From source file:com.deliciousdroid.fragment.ViewBookmarkFragment.java

private void addTag(SpannableStringBuilder builder, Tag t, TagSpan.OnTagClickListener listener) {
    int flags = 0;

    if (builder.length() != 0) {
        builder.append("  ");
    }/*ww w .ja va 2  s . c o m*/

    int start = builder.length();
    builder.append(t.getTagName());
    int end = builder.length();

    TagSpan span = new TagSpan(t.getTagName());
    span.setOnTagClickListener(listener);

    builder.setSpan(span, start, end, flags);
}

From source file:tw.idv.gasolin.pycontw2012.ui.SessionDetailFragment.java

/**
 * Handle {@link SessionsQuery} {@link Cursor}.
 *///  w  ww.ja v a  2  s  .c  o m
private void onSessionQueryComplete(Cursor cursor) {
    try {
        mSessionCursor = true;
        if (!cursor.moveToFirst()) {
            return;
        }

        // Format time block this session occupies
        final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START);
        final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END);
        final Locale locale = getResources().getConfiguration().locale;
        final String roomName = UIUtils.getBestLocaleString(locale, cursor.getString(SessionsQuery.ROOM_NAME),
                cursor.getString(SessionsQuery.ROOM_NAME_ZH_TW),
                cursor.getString(SessionsQuery.ROOM_NAME_ZH_CN));
        final String subtitle = UIUtils.formatSessionSubtitle(blockStart, blockEnd, roomName, getActivity());

        mTitleString = cursor.getString(SessionsQuery.TITLE);
        mTitle.setText(mTitleString);
        mSubtitle.setText(subtitle);

        mUrl = cursor.getString(SessionsQuery.URL);
        if (TextUtils.isEmpty(mUrl)) {
            mUrl = "";
        }

        mHashtag = cursor.getString(SessionsQuery.HASHTAG);
        mTagDisplay = (TextView) mRootView.findViewById(R.id.session_tags_button);
        if (!TextUtils.isEmpty(mHashtag)) {
            // Create the button text
            SpannableStringBuilder sb = new SpannableStringBuilder();
            sb.append(getString(R.string.tag_stream) + " ");
            int boldStart = sb.length();
            sb.append(getHashtagsString());
            sb.setSpan(sBoldSpan, boldStart, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            mTagDisplay.setText(sb);

            mTagDisplay.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), TagStreamActivity.class);
                    intent.putExtra(TagStreamFragment.EXTRA_QUERY, getHashtagsString());
                    startActivity(intent);
                }
            });
        } else {
            mTagDisplay.setVisibility(View.GONE);
        }

        mRoomId = cursor.getString(SessionsQuery.ROOM_ID);

        // Unregister around setting checked state to avoid triggering
        // listener since change isn't user generated.
        mStarred.setOnCheckedChangeListener(null);
        mStarred.setChecked(cursor.getInt(SessionsQuery.STARRED) != 0);
        mStarred.setOnCheckedChangeListener(this);

        final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT);
        if (!TextUtils.isEmpty(sessionAbstract)) {
            UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract);
            mAbstract.setVisibility(View.VISIBLE);
            mHasSummaryContent = true;
        } else {
            mAbstract.setVisibility(View.GONE);
        }

        // Show empty message when all data is loaded, and nothing to show
        if (mSpeakersCursor && !mHasSummaryContent) {
            mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
        }

        AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sessions/" + mTitleString);

        updateLinksTab(cursor);

    } finally {
        cursor.close();
    }
}

From source file:org.sufficientlysecure.keychain.ui.ViewKeyKeybaseFragment.java

@Override
public void onCryptoOperationError(KeybaseVerificationResult result) {

    result.createNotify(getActivity()).show();

    SpannableStringBuilder ssb = new SpannableStringBuilder();

    ssb.append(getString(R.string.keybase_proof_failure));
    String msg = getString(result.getLog().getLast().mType.mMsgId);
    if (msg == null) {
        msg = getString(R.string.keybase_unknown_proof_failure);
    }//from  w w  w. ja  v a 2  s.  c  o  m
    StyleSpan bold = new StyleSpan(Typeface.BOLD);
    ssb.setSpan(bold, 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.append("\n\n").append(msg);

    displaySpannableResult(ssb);
}

From source file:com.gh4a.activities.IssueActivity.java

private void fillData() {
    // set details inside listview header
    ImageView ivGravatar = (ImageView) mListHeaderView.findViewById(R.id.iv_gravatar);
    AvatarHandler.assignAvatar(ivGravatar, mIssue.getUser());
    ivGravatar.setOnClickListener(this);

    TextView tvState = (TextView) mHeader.findViewById(R.id.tv_state);
    boolean closed = Constants.Issue.STATE_CLOSED.equals(mIssue.getState());
    int stateTextResId = closed ? R.string.closed : R.string.open;
    int stateColorAttributeId = closed ? R.attr.colorIssueClosed : R.attr.colorIssueOpen;

    tvState.setText(getString(stateTextResId).toUpperCase(Locale.getDefault()));
    transitionHeaderToColor(stateColorAttributeId,
            closed ? R.attr.colorIssueClosedDark : R.attr.colorIssueOpenDark);
    UiUtils.trySetListOverscrollColor(mRecyclerView, UiUtils.resolveColor(this, stateColorAttributeId));

    TextView tvExtra = (TextView) mListHeaderView.findViewById(R.id.tv_extra);
    tvExtra.setText(ApiHelpers.getUserLogin(this, mIssue.getUser()));

    TextView tvTimestamp = (TextView) mListHeaderView.findViewById(R.id.tv_timestamp);
    tvTimestamp.setText(StringUtils.formatRelativeTime(this, mIssue.getCreatedAt(), true));

    TextView tvTitle = (TextView) mHeader.findViewById(R.id.tv_title);
    tvTitle.setText(mIssue.getTitle());//w  w  w. j a v  a 2 s.co m

    String body = mIssue.getBodyHtml();
    TextView descriptionView = (TextView) mListHeaderView.findViewById(R.id.tv_desc);
    if (!StringUtils.isBlank(body)) {
        body = HtmlUtils.format(body).toString();
        mImageGetter.bind(descriptionView, body, mIssue.getNumber());
    }
    descriptionView.setMovementMethod(UiUtils.CHECKING_LINK_METHOD);

    View milestoneGroup = mListHeaderView.findViewById(R.id.milestone_container);
    if (mIssue.getMilestone() != null) {
        TextView tvMilestone = (TextView) mListHeaderView.findViewById(R.id.tv_milestone);
        tvMilestone.setText(mIssue.getMilestone().getTitle());
        milestoneGroup.setVisibility(View.VISIBLE);
    } else {
        milestoneGroup.setVisibility(View.GONE);
    }

    View assigneeGroup = mListHeaderView.findViewById(R.id.assignee_container);
    if (mIssue.getAssignee() != null) {
        TextView tvAssignee = (TextView) mListHeaderView.findViewById(R.id.tv_assignee);
        tvAssignee.setText(mIssue.getAssignee().getLogin());

        ImageView ivAssignee = (ImageView) mListHeaderView.findViewById(R.id.iv_assignee);
        AvatarHandler.assignAvatar(ivAssignee, mIssue.getAssignee());
        ivAssignee.setOnClickListener(this);
        assigneeGroup.setVisibility(View.VISIBLE);
    } else {
        assigneeGroup.setVisibility(View.GONE);
    }

    List<Label> labels = mIssue.getLabels();
    View labelGroup = mListHeaderView.findViewById(R.id.label_container);
    if (labels != null && !labels.isEmpty()) {
        TextView labelView = (TextView) mListHeaderView.findViewById(R.id.labels);
        SpannableStringBuilder builder = new SpannableStringBuilder();

        for (Label label : labels) {
            int pos = builder.length();
            IssueLabelSpan span = new IssueLabelSpan(this, label, true);
            builder.append(label.getName());
            builder.setSpan(span, pos, pos + label.getName().length(), 0);
        }
        labelView.setText(builder);
        labelGroup.setVisibility(View.VISIBLE);
    } else {
        labelGroup.setVisibility(View.GONE);
    }

    TextView tvPull = (TextView) mListHeaderView.findViewById(R.id.tv_pull);
    if (mIssue.getPullRequest() != null && mIssue.getPullRequest().getDiffUrl() != null) {
        tvPull.setVisibility(View.VISIBLE);
        tvPull.setOnClickListener(this);
    } else {
        tvPull.setVisibility(View.GONE);
    }

    mHeader.setVisibility(View.VISIBLE);
    updateFabVisibility();
    updateCommentLockState();
}

From source file:jp.gr.java_conf.piropiroping.bluetoothcommander.MainActivity.java

private void convertBitmapCommand(String command, int start, int stop) {
    //???/*from ww  w . j  a va2 s  . c o m*/
    Paint objPaint = new Paint();
    Bitmap objBitmap;
    Canvas objCanvas;
    int textSize = 40;
    int textWidth = textSize * command.length(), textHeight = textSize;

    objPaint.setAntiAlias(true);
    objPaint.setColor(Color.BLUE);
    objPaint.setTextSize(textSize);
    Paint.FontMetrics fm = objPaint.getFontMetrics();
    objPaint.getTextBounds(command, 0, command.length(), new Rect(0, 0, textWidth, textHeight));

    //?
    textWidth = (int) objPaint.measureText(command);
    textHeight = (int) (Math.abs(fm.top) + fm.bottom);
    objBitmap = Bitmap.createBitmap(textWidth, textHeight, Bitmap.Config.ARGB_8888);

    //???
    objCanvas = new Canvas(objBitmap);
    objCanvas.drawText(command, 0, Math.abs(fm.top), objPaint);

    Editable editable = mOutEditText.getText();
    SpannableStringBuilder ssb = (SpannableStringBuilder) editable;
    ImageSpan is = new ImageSpan(getApplicationContext(), objBitmap);
    ssb.setSpan(is, start, stop + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

From source file:com.pindroid.fragment.ViewBookmarkFragment.java

private void loadBookmark() {
    if (bookmark != null) {
        if (viewType == BookmarkViewType.VIEW) {

            Date d = new Date(bookmark.getTime());

            if (bookmark.getDescription() != null && !bookmark.getDescription().equals("null"))
                mTitle.setText(bookmark.getDescription());

            mUrl.setText(bookmark.getUrl());

            if (bookmark.getNotes() != null && !bookmark.getNotes().equals("null")
                    && !bookmark.getNotes().equals("")) {
                mNotes.setText(bookmark.getNotes());
                notesSection.setVisibility(View.VISIBLE);
            } else {
                notesSection.setVisibility(View.GONE);
            }/*w  w  w . j  a  va2 s  .  c  o m*/

            mTime.setText(d.toString());

            mTags.setMovementMethod(LinkMovementMethod.getInstance());
            SpannableStringBuilder tagBuilder = new SpannableStringBuilder();

            if (bookmark.getTags().size() > 0) {
                for (Tag t : bookmark.getTags()) {
                    addTag(tagBuilder, t, tagOnClickListener);
                }

                mTags.setText(tagBuilder);

                tagsSection.setVisibility(View.VISIBLE);
            } else {
                tagsSection.setVisibility(View.GONE);
            }

            if (isMyself()) {
                Uri.Builder ub = new Uri.Builder();
                ub.scheme("content");
                ub.authority(BookmarkContentProvider.AUTHORITY);
                ub.appendPath("bookmark");
                ub.appendPath(Integer.toString(bookmark.getId()));

                getActivity().getContentResolver().unregisterContentObserver(observer);
                getActivity().getContentResolver().registerContentObserver(ub.build(), true, observer);

                mUsername.setText(bookmark.getAccount());

                if (bookmark.getToRead() && bookmark.getShared()) {
                    bookmarkIcon.setImageResource(R.drawable.ic_unread);
                } else if (!bookmark.getToRead() && bookmark.getShared()) {
                    bookmarkIcon.setImageResource(R.drawable.ic_bookmark);
                } else if (bookmark.getToRead() && !bookmark.getShared()) {
                    bookmarkIcon.setImageResource(R.drawable.ic_unread_private);
                } else if (!bookmark.getToRead() && !bookmark.getShared()) {
                    bookmarkIcon.setImageResource(R.drawable.ic_bookmark_private);
                }

            } else {
                if (bookmark.getAccount() != null) {
                    SpannableStringBuilder builder = new SpannableStringBuilder();
                    int start = builder.length();
                    builder.append(bookmark.getAccount());
                    int end = builder.length();

                    AccountSpan span = new AccountSpan(bookmark.getAccount());
                    span.setOnAccountClickListener(accountOnClickListener);

                    builder.setSpan(span, start, end, 0);

                    mUsername.setText(builder);
                }

                mUsername.setMovementMethod(LinkMovementMethod.getInstance());
            }
        } else if (viewType == BookmarkViewType.READ) {
            showInWebView(Constants.INSTAPAPER_URL + bookmark.getUrl());

            if (isMyself() && bookmark.getToRead() && SettingsHelper.getMarkAsRead(getActivity()))
                bookmarkSelectedListener.onBookmarkMark(bookmark);
        } else if (viewType == BookmarkViewType.WEB) {
            showInWebView(bookmark.getUrl());
        }
    } else {
        clearView();
    }
}