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.google.android.apps.location.gps.gnsslogger.PlotFragment.java

/**
 *  Updates the CN0 versus Time plot data from a {@link GnssMeasurement}
 *///from w w  w.j  a v  a 2s. c om
protected void updateCnoTab(GnssMeasurementsEvent event) {
    long timeInSeconds = TimeUnit.NANOSECONDS.toSeconds(event.getClock().getTimeNanos());
    if (mInitialTimeSeconds < 0) {
        mInitialTimeSeconds = timeInSeconds;
    }

    // Building the texts message in analysis text view
    List<GnssMeasurement> measurements = sortByCarrierToNoiseRatio(new ArrayList<>(event.getMeasurements()));
    SpannableStringBuilder builder = new SpannableStringBuilder();
    double currentAverage = 0;
    if (measurements.size() >= NUMBER_OF_STRONGEST_SATELLITES) {
        mAverageCn0 = (mAverageCn0 * mMeasurementCount
                + (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz()
                        + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz())
                        / NUMBER_OF_STRONGEST_SATELLITES)
                / (++mMeasurementCount);
        currentAverage = (measurements.get(0).getCn0DbHz() + measurements.get(1).getCn0DbHz()
                + measurements.get(2).getCn0DbHz() + measurements.get(3).getCn0DbHz())
                / NUMBER_OF_STRONGEST_SATELLITES;
    }
    builder.append(getString(R.string.history_average_hint, sDataFormat.format(mAverageCn0) + "\n"));
    builder.append(getString(R.string.current_average_hint, sDataFormat.format(currentAverage) + "\n"));
    for (int i = 0; i < NUMBER_OF_STRONGEST_SATELLITES && i < measurements.size(); i++) {
        int start = builder.length();
        builder.append(mDataSetManager.getConstellationPrefix(measurements.get(i).getConstellationType())
                + measurements.get(i).getSvid() + ": " + sDataFormat.format(measurements.get(i).getCn0DbHz())
                + "\n");
        int end = builder.length();
        builder.setSpan(
                new ForegroundColorSpan(mColorMap.getColor(measurements.get(i).getSvid(),
                        measurements.get(i).getConstellationType())),
                start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    builder.append(getString(R.string.satellite_number_sum_hint, measurements.size()));
    mAnalysisView.setText(builder);

    // Adding incoming data into Dataset
    mLastTimeReceivedSeconds = timeInSeconds - mInitialTimeSeconds;
    for (GnssMeasurement measurement : measurements) {
        int constellationType = measurement.getConstellationType();
        int svID = measurement.getSvid();
        if (constellationType != GnssStatus.CONSTELLATION_UNKNOWN) {
            mDataSetManager.addValue(CN0_TAB, constellationType, svID, mLastTimeReceivedSeconds,
                    measurement.getCn0DbHz());
        }
    }

    mDataSetManager.fillInDiscontinuity(CN0_TAB, mLastTimeReceivedSeconds);

    // Checks if the plot has reached the end of frame and resize
    if (mLastTimeReceivedSeconds > mCurrentRenderer.getXAxisMax()) {
        mCurrentRenderer.setXAxisMax(mLastTimeReceivedSeconds);
        mCurrentRenderer.setXAxisMin(mLastTimeReceivedSeconds - TIME_INTERVAL_SECONDS);
    }

    mChartView.invalidate();
}

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

public static CharSequence generateSearchName(String name, String name2, String q) {
    if (name == null && name2 == null) {
        return "";
    }/*from w w w  .  jav a  2  s. c  om*/
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String wholeString = name;
    if (wholeString == null || wholeString.length() == 0) {
        wholeString = name2;
    } else if (name2 != null && name2.length() != 0) {
        wholeString += " " + name2;
    }
    wholeString = wholeString.trim();
    String lower = " " + wholeString.toLowerCase();

    int index;
    int lastIndex = 0;
    while ((index = lower.indexOf(" " + q, lastIndex)) != -1) {
        int idx = index - (index == 0 ? 0 : 1);
        int end = q.length() + (index == 0 ? 0 : 1) + idx;

        if (lastIndex != 0 && lastIndex != idx + 1) {
            builder.append(wholeString.substring(lastIndex, idx));
        } else if (lastIndex == 0 && idx != 0) {
            builder.append(wholeString.substring(0, idx));
        }

        String query = wholeString.substring(idx, Math.min(wholeString.length(), end));
        if (query.startsWith(" ")) {
            builder.append(" ");
        }
        query = query.trim();

        int start = builder.length();
        builder.append(query);
        builder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText4)),
                start, start + query.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        lastIndex = end;
    }

    if (lastIndex != -1 && lastIndex != wholeString.length()) {
        builder.append(wholeString.substring(lastIndex, wholeString.length()));
    }

    return builder;
}

From source file:com.hippo.ehviewer.ui.scene.GalleryListScene.java

private void setSearchBarHint(Context context, SearchBar searchBar) {
    Resources resources = context.getResources();
    Drawable searchImage = DrawableManager.getDrawable(context, R.drawable.v_magnify_x24);
    SpannableStringBuilder ssb = new SpannableStringBuilder("   ");
    ssb.append(resources.getString(//from  w  w w  .  ja  v a  2 s.c o m
            EhUrl.SITE_EX == Settings.getGallerySite() ? R.string.gallery_list_search_bar_hint_exhentai
                    : R.string.gallery_list_search_bar_hint_e_hentai));
    int textSize = (int) (searchBar.getEditTextTextSize() * 1.25);
    if (searchImage != null) {
        searchImage.setBounds(0, 0, textSize, textSize);
        ssb.setSpan(new ImageSpan(searchImage), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    searchBar.setEditTextHint(ssb);
}

From source file:ru.valle.btc.MainActivity.java

private void showSpendPanelForKeyPair(KeyPair keyPair) {
    if (keyPair != null && keyPair.privateKey.privateKeyDecoded == null) {
        keyPair = null;//from  w  w  w . ja v a  2  s. co  m
    }
    if (keyPair != null && !TextUtils.isEmpty(keyPair.address)) {
        currentKeyPair = keyPair;
        final String address = keyPair.address;
        String descStr = getString(R.string.raw_tx_description_header, address);
        SpannableStringBuilder builder = new SpannableStringBuilder(descStr);
        int spanBegin = descStr.indexOf(address);
        if (spanBegin >= 0) {
            ForegroundColorSpan addressColorSpan = new ForegroundColorSpan(
                    getColor(MainActivity.this, R.color.dark_orange));
            builder.setSpan(addressColorSpan, spanBegin, spanBegin + address.length(),
                    SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
        }
        rawTxDescriptionHeaderView.setText(builder);
        String wutLink = getString(R.string.raw_tx_description_wut_link);
        String jsonLink = getString(R.string.raw_tx_description_json_link);
        builder = new SpannableStringBuilder(getString(R.string.raw_tx_description, wutLink, jsonLink));

        spanBegin = builder.toString().indexOf(wutLink);
        ClickableSpan urlSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                SpannableStringBuilder builder = new SpannableStringBuilder(
                        getText(R.string.raw_tx_description_wut));
                setUrlSpanForAddress("blockexplorer.com", address, builder);
                setUrlSpanForAddress("blockchain.info", address, builder);
                TextView messageView = new TextView(MainActivity.this);
                messageView.setText(builder);
                messageView.setMovementMethod(LinkMovementMethod.getInstance());
                int padding = (int) (16 * (getResources().getDisplayMetrics().densityDpi / 160f));
                messageView.setPadding(padding, padding, padding, padding);
                new AlertDialog.Builder(MainActivity.this).setView(messageView)
                        .setPositiveButton(android.R.string.ok, null).show();
            }
        };
        builder.setSpan(urlSpan, spanBegin, spanBegin + wutLink.length(),
                SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);

        spanBegin = builder.toString().indexOf(jsonLink);
        urlSpan = new URLSpan("http://blockchain.info/unspent?active=" + address);
        builder.setSpan(urlSpan, spanBegin, spanBegin + jsonLink.length(),
                SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);

        rawTxDescriptionView.setText(builder);
        rawTxDescriptionView.setMovementMethod(LinkMovementMethod.getInstance());
        onUnspentOutputsInfoChanged();
    }
    sendLayout.setVisibility(keyPair != null ? View.VISIBLE : View.GONE);
    enterPrivateKeyAck.setVisibility(keyPair == null ? View.VISIBLE : View.GONE);
}

From source file:com.amazon.android.ui.widget.EllipsizedTextView.java

/**
 * Sets ellipsis properties./* ww w .  j  av a 2 s.  c  om*/
 *
 * @param widthMeasureSpec  Ellipsis width.
 * @param heightMeasureSpec Ellipsis height.
 * @param layout            Layout for ellipsis.
 * @param lastLine          Last line length for ellipsis.
 * @param maxLines          Max lines in ellipsis.
 */
private void setEllipsis(int widthMeasureSpec, int heightMeasureSpec, Layout layout, int lastLine,
        int maxLines) {

    mIsEllipsized = true;
    setFocusable(true);
    setClickable(true);
    final SpannableString ss = new SpannableString(mCharSequence);
    String visibleText = mCharSequence.toString();

    mEllipsisImage = new StateImageSpan(getContext(), mGuillemetDrawableId, ImageSpan.ALIGN_BASELINE);

    final SpannableStringBuilder spannedText = new SpannableStringBuilder();
    int ellipsisIndex = layout.getLineStart(Math.min(lastLine + 1, maxLines));

    // Keep chopping words off until the ellipsis is on a visible line or there is only one
    // line left.
    do {
        // Only truncate the last line for long description.
        if (lastLine >= maxLines) {
            // Getting the first word break index before the last index of maxline.
            int safeBreakIndex = breakBefore(visibleText, ellipsisIndex, BreakIterator.getWordInstance());
            final int maxLineStart = layout.getLineStart(maxLines - 1);

            // If this check pass, it means we just truncated a word that is longer than a line.
            if (safeBreakIndex < maxLineStart) {
                // Need to check character by character and break in the middle now. Checking
                // word by word should cover most cases, only do this if a word is longer than
                // line width.
                safeBreakIndex = breakBefore(visibleText, ellipsisIndex, BreakIterator.getCharacterInstance());
            }
            ellipsisIndex = safeBreakIndex;
        }

        visibleText = visibleText.substring(0, ellipsisIndex);
        final CharSequence charOutput = ss.subSequence(0, ellipsisIndex);

        // Re-add ellipsis and convert to image
        spannedText.replace(0, spannedText.length(), charOutput);
        spannedText.append(ELLIPSIS);

        spannedText.setSpan(mEllipsisImage, ellipsisIndex, ellipsisIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

        // Reset text and re-measure.
        super.setText(spannedText, BufferType.SPANNABLE);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    } while (getLineCount() > getMaxLines() && getLineCount() > 1);
    requestFocus();
}

From source file:com.battlelancer.seriesguide.ui.EpisodeDetailsFragment.java

private void populateEpisodeData(Cursor cursor) {
    if (cursor == null || !cursor.moveToFirst()) {
        // no data to display
        if (mEpisodeContainer != null) {
            mEpisodeContainer.setVisibility(View.GONE);
        }/*w w  w. j  a v a  2 s .  c o  m*/
        return;
    }

    mShowTvdbId = cursor.getInt(DetailsQuery.REF_SHOW_ID);
    mSeasonNumber = cursor.getInt(DetailsQuery.SEASON);
    mEpisodeNumber = cursor.getInt(DetailsQuery.NUMBER);
    mShowRunTime = cursor.getInt(DetailsQuery.SHOW_RUNTIME);
    mEpisodeReleaseTime = cursor.getLong(DetailsQuery.FIRST_RELEASE_MS);

    // title and description
    mEpisodeTitle = cursor.getString(DetailsQuery.TITLE);
    mTitle.setText(mEpisodeTitle);
    mDescription.setText(cursor.getString(DetailsQuery.OVERVIEW));

    // show title
    mShowTitle = cursor.getString(DetailsQuery.SHOW_TITLE);

    // release time and day
    SpannableStringBuilder timeAndNumbersText = new SpannableStringBuilder();
    if (mEpisodeReleaseTime != -1) {
        Date actualRelease = TimeTools.getEpisodeReleaseTime(getActivity(), mEpisodeReleaseTime);
        mReleaseDay.setText(TimeTools.formatToDate(getActivity(), actualRelease));
        // "in 15 mins (Fri)"
        timeAndNumbersText.append(getString(R.string.release_date_and_day,
                TimeTools.formatToRelativeLocalReleaseTime(getActivity(), actualRelease),
                TimeTools.formatToLocalReleaseDay(actualRelease)).toUpperCase(Locale.getDefault()));
        timeAndNumbersText.append("  ");
    } else {
        mReleaseDay.setText(R.string.unknown);
    }
    // absolute number (e.g. relevant for Anime): "ABSOLUTE 142"
    int numberStartIndex = timeAndNumbersText.length();
    int absoluteNumber = cursor.getInt(DetailsQuery.ABSOLUTE_NUMBER);
    if (absoluteNumber > 0) {
        timeAndNumbersText.append(getString(R.string.episode_number_absolute)).append(" ")
                .append(String.valueOf(absoluteNumber));
        // de-emphasize number
        timeAndNumbersText.setSpan(new TextAppearanceSpan(getActivity(), R.style.TextAppearance_Caption_Dim),
                numberStartIndex, timeAndNumbersText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    mReleaseTime.setText(timeAndNumbersText);

    // guest stars
    Utils.setLabelValueOrHide(mLabelGuestStars, mGuestStars,
            Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.GUESTSTARS)));
    // DVD episode number
    Utils.setLabelValueOrHide(mLabelDvd, mDvd, cursor.getDouble(DetailsQuery.DVDNUMBER));
    // directors
    Utils.setValueOrPlaceholder(mDirectors,
            Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.DIRECTORS)));
    // writers
    Utils.setValueOrPlaceholder(mWriters, Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.WRITERS)));

    // last TVDb edit date
    long lastEditSeconds = cursor.getLong(DetailsQuery.LASTEDIT);
    if (lastEditSeconds > 0) {
        mLastEdit.setText(DateUtils.formatDateTime(getActivity(), lastEditSeconds * 1000,
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME));
    } else {
        mLastEdit.setText(R.string.unknown);
    }

    // ratings
    mRatingsContainer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            rateOnTrakt();
        }
    });
    mRatingsContainer.setFocusable(true);
    CheatSheet.setup(mRatingsContainer, R.string.action_rate);
    // TVDb rating
    String tvdbRating = cursor.getString(DetailsQuery.RATING);
    if (!TextUtils.isEmpty(tvdbRating)) {
        mTvdbRating.setText(tvdbRating);
    }
    // trakt ratings
    loadTraktRatings(true);

    // episode image
    final String imagePath = cursor.getString(DetailsQuery.IMAGE);
    mImageContainer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent fullscreen = new Intent(getActivity(), FullscreenImageActivity.class);
            fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_PATH, imagePath);
            ActivityCompat.startActivity(getActivity(), fullscreen, ActivityOptionsCompat
                    .makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()).toBundle());
        }
    });
    loadImage(imagePath);

    // check in button
    final int episodeTvdbId = cursor.getInt(DetailsQuery._ID);
    mCheckinButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // display a check-in dialog
            CheckInDialogFragment f = CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId);
            f.show(getFragmentManager(), "checkin-dialog");
            fireTrackerEvent("Check-In");
        }
    });
    CheatSheet.setup(mCheckinButton);

    // watched button
    mEpisodeFlag = cursor.getInt(DetailsQuery.WATCHED);
    boolean isWatched = EpisodeTools.isWatched(mEpisodeFlag);
    Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mWatchedButton, 0,
            isWatched ? Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatched)
                    : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatch),
            0, 0);
    mWatchedButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // disable button, will be re-enabled on data reload once action completes
            v.setEnabled(false);
            onToggleWatched();
            fireTrackerEvent("Toggle watched");
        }
    });
    mWatchedButton.setEnabled(true);
    mWatchedButton.setText(isWatched ? R.string.action_unwatched : R.string.action_watched);
    CheatSheet.setup(mWatchedButton, isWatched ? R.string.action_unwatched : R.string.action_watched);

    // collected button
    mCollected = cursor.getInt(DetailsQuery.COLLECTED) == 1;
    Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mCollectedButton, 0,
            mCollected ? R.drawable.ic_collected
                    : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableCollect),
            0, 0);
    mCollectedButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // disable button, will be re-enabled on data reload once action completes
            v.setEnabled(false);
            onToggleCollected();
            fireTrackerEvent("Toggle collected");
        }
    });
    mCollectedButton.setEnabled(true);
    mCollectedButton.setText(mCollected ? R.string.action_collection_remove : R.string.action_collection_add);
    CheatSheet.setup(mCollectedButton,
            mCollected ? R.string.action_collection_remove : R.string.action_collection_add);

    // skip button
    boolean isSkipped = EpisodeTools.isSkipped(mEpisodeFlag);
    if (isWatched) {
        // if watched do not allow skipping
        mSkipButton.setVisibility(View.INVISIBLE);
    } else {
        mSkipButton.setVisibility(View.VISIBLE);
        Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mSkipButton, 0,
                isSkipped ? R.drawable.ic_skipped
                        : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableSkip),
                0, 0);
        mSkipButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // disable button, will be re-enabled on data reload once action completes
                v.setEnabled(false);
                onToggleSkipped();
                fireTrackerEvent("Toggle skipped");
            }
        });
        mSkipButton.setText(isSkipped ? R.string.action_dont_skip : R.string.action_skip);
        CheatSheet.setup(mSkipButton, isSkipped ? R.string.action_dont_skip : R.string.action_skip);
    }
    mSkipButton.setEnabled(true);

    // service buttons
    ServiceUtils.setUpTraktButton(mShowTvdbId, mSeasonNumber, mEpisodeNumber, mTraktButton, TAG);
    // IMDb
    String imdbId = cursor.getString(DetailsQuery.IMDBID);
    if (TextUtils.isEmpty(imdbId)) {
        // fall back to show IMDb id
        imdbId = cursor.getString(DetailsQuery.SHOW_IMDBID);
    }
    ServiceUtils.setUpImdbButton(imdbId, mImdbButton, TAG, getActivity());
    // TVDb
    final int seasonTvdbId = cursor.getInt(DetailsQuery.REF_SEASON_ID);
    ServiceUtils.setUpTvdbButton(mShowTvdbId, seasonTvdbId, getEpisodeTvdbId(), mTvdbButton, TAG);
    // trakt comments
    mCommentsButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), TraktShoutsActivity.class);
            intent.putExtras(TraktShoutsActivity.createInitBundleEpisode(mShowTvdbId, mSeasonNumber,
                    mEpisodeNumber, mEpisodeTitle));
            ActivityCompat.startActivity(getActivity(), intent, ActivityOptionsCompat
                    .makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()).toBundle());
            fireTrackerEvent("Comments");
        }
    });

    mEpisodeContainer.setVisibility(View.VISIBLE);
}

From source file:org.getlantern.firetweet.fragment.support.UserFragment.java

private void updateTitleColor() {
    final int[] location = new int[2];
    mNameView.getLocationOnScreen(location);
    final float nameShowingRatio = (mHeaderDrawerLayout.getPaddingTop() - location[1])
            / (float) mNameView.getHeight();
    final int textAlpha = Math.round(0xFF * MathUtils.clamp(nameShowingRatio, 0, 1));
    final FragmentActivity activity = getActivity();
    final SpannableStringBuilder spannedTitle;
    final CharSequence title = activity.getTitle();
    if (title instanceof SpannableStringBuilder) {
        spannedTitle = (SpannableStringBuilder) title;
    } else {//w w  w.  j  a  va 2  s .  com
        spannedTitle = SpannableStringBuilder.valueOf(title);
    }
    final TextAlphaSpan[] spans = spannedTitle.getSpans(0, spannedTitle.length(), TextAlphaSpan.class);
    if (spans.length > 0) {
        spans[0].setAlpha(textAlpha);
    } else {
        spannedTitle.setSpan(new TextAlphaSpan(textAlpha), 0, spannedTitle.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    activity.setTitle(spannedTitle);
}

From source file:lewa.support.v7.widget.SearchView.java

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);/*from w  w  w.j a  va2 s . co  m*/
    Drawable searchIcon = getContext().getResources().getDrawable(mSearchIconResId);
    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;
}

From source file:cm.aptoide.com.actionbarsherlock.widget.SearchView.java

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);//ww w .j  ava2 s  . c  o m
    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;
}

From source file:com.csipsimple.ui.incall.CallActivity.java

/**
 * Controls buttons (accept, reject etc).
 * @param whichAction what action has been done
 * @param call/*from   ww  w.j a  va  2s . c o  m*/
 */
@Override
public void onTrigger(int whichAction, final SipCallSession call) {

    // Sanity check for actions requiring valid call id
    if (whichAction == TAKE_CALL || whichAction == REJECT_CALL || whichAction == DONT_TAKE_CALL
            || whichAction == TERMINATE_CALL || whichAction == DETAILED_DISPLAY || whichAction == TOGGLE_HOLD
            || whichAction == START_RECORDING || whichAction == STOP_RECORDING || whichAction == DTMF_DISPLAY
            || whichAction == XFER_CALL || whichAction == TRANSFER_CALL || whichAction == START_VIDEO
            || whichAction == STOP_VIDEO) {
        // We check that current call is valid for any actions
        if (call == null) {
            Log.e(TAG, "Try to do an action on a null call !!!");
            return;
        }
        if (call.getCallId() == SipCallSession.INVALID_CALL_ID) {
            Log.e(TAG, "Try to do an action on an invalid call !!!");
            return;
        }
    }

    // Reset proximity sensor timer
    proximityManager.restartTimer();

    try {
        switch (whichAction) {
        case TAKE_CALL: {
            if (service != null) {
                Log.i(TAG, "Answering call " + call.getCallId());

                boolean shouldHoldOthers = false;

                // Well actually we should be always before confirmed
                if (call.isBeforeConfirmed()) {
                    shouldHoldOthers = true;
                }

                service.answer(call.getCallId(), StatusCode.OK);

                // if it's a ringing call, we assume that user wants to
                // hold other calls
                if (shouldHoldOthers && callsInfo != null) {
                    for (SipCallSession callInfo : callsInfo) {
                        // For each active and running call
                        if (SipCallSession.InvState.CONFIRMED == callInfo.getCallState()
                                && !callInfo.isLocalHeld() && callInfo.getCallId() != call.getCallId()) {

                            Log.d(TAG, "Hold call " + callInfo.getCallId());
                            service.hold(callInfo.getCallId());

                        }
                    }
                }
            }
            break;
        }
        case DONT_TAKE_CALL: {
            if (service != null) {
                Log.i(TAG, "Rejecting the call with BUSY_HERE");
                service.hangup(call.getCallId(), StatusCode.BUSY_HERE);
            }
            break;
        }
        case REJECT_CALL:
            if (service != null) {
                Log.i(TAG, "Rejecting the call");
                service.hangup(call.getCallId(), 0);
            }
            break;
        case TERMINATE_CALL: {
            if (service != null) {
                Log.i(TAG, "Terminating the call");
                service.hangup(call.getCallId(), 0);
            }
            break;
        }
        case CANCEL_CALL: {
            if (service != null) {
                Log.i(TAG, "Cancelling the call");
                service.hangup(call.getCallId(), 0);
            }
            sendCancelCallBroadcast();
            break;
        }
        case MUTE_ON:
        case MUTE_OFF: {
            if (service != null) {
                Log.i(TAG, "Set mute " + (whichAction == MUTE_ON));
                service.setMicrophoneMute((whichAction == MUTE_ON) ? true : false);
            }
            break;
        }
        case SPEAKER_ON:
        case SPEAKER_OFF: {
            if (service != null) {
                Log.d(TAG, "Set speaker " + (whichAction == SPEAKER_ON));
                useAutoDetectSpeaker = false;
                service.setSpeakerphoneOn((whichAction == SPEAKER_ON) ? true : false);
            }
            break;
        }
        case BLUETOOTH_ON:
        case BLUETOOTH_OFF: {
            if (service != null) {
                Log.d(TAG, "Set bluetooth " + (whichAction == BLUETOOTH_ON));
                service.setBluetoothOn((whichAction == BLUETOOTH_ON) ? true : false);
            }
            break;
        }
        case DTMF_DISPLAY: {
            Log.d(TAG, "DTMF_DISPLAY");
            showDialpad(call.getCallId());
            break;
        }
        case DETAILED_DISPLAY: {
            if (service != null) {
                if (infoDialog != null) {
                    infoDialog.dismiss();
                }
                String infos = service.showCallInfosDialog(call.getCallId());
                String natType = service.getLocalNatType();
                SpannableStringBuilder buf = new SpannableStringBuilder();
                Builder builder = new Builder(this);

                buf.append(infos);
                if (!TextUtils.isEmpty(natType)) {
                    buf.append("\r\nLocal NAT type detected : ");
                    buf.append(natType);
                }
                TextAppearanceSpan textSmallSpan = new TextAppearanceSpan(this,
                        android.R.style.TextAppearance_Small);
                buf.setSpan(textSmallSpan, 0, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                infoDialog = builder.setIcon(android.R.drawable.ic_dialog_info).setMessage(buf)
                        .setNeutralButton(R.string.ok, null).create();
                infoDialog.show();
            }
            break;
        }
        case TOGGLE_HOLD: {
            if (service != null) {
                // Log.d(TAG,
                // "Current state is : "+callInfo.getCallState().name()+" / "+callInfo.getMediaStatus().name());
                if (call.getMediaStatus() == SipCallSession.MediaState.LOCAL_HOLD
                        || call.getMediaStatus() == SipCallSession.MediaState.NONE) {
                    service.reinvite(call.getCallId(), true);
                } else {
                    service.hold(call.getCallId());
                }
            }
            break;
        }
        case MEDIA_SETTINGS: {
            startActivity(new Intent(this, InCallMediaControl.class));
            break;
        }
        case XFER_CALL: {
            Intent pickupIntent = new Intent(this, PickupSipUri.class);
            pickupIntent.putExtra(CALL_ID, call.getCallId());
            startActivityForResult(pickupIntent, PICKUP_SIP_URI_XFER);
            break;
        }
        case TRANSFER_CALL: {
            final ArrayList<SipCallSession> remoteCalls = new ArrayList<SipCallSession>();
            if (callsInfo != null) {
                for (SipCallSession remoteCall : callsInfo) {
                    // Verify not current call
                    if (remoteCall.getCallId() != call.getCallId() && remoteCall.isOngoing()) {
                        remoteCalls.add(remoteCall);
                    }
                }
            }

            if (remoteCalls.size() > 0) {
                Builder builder = new Builder(this);
                CharSequence[] simpleAdapter = new String[remoteCalls.size()];
                for (int i = 0; i < remoteCalls.size(); i++) {
                    simpleAdapter[i] = remoteCalls.get(i).getRemoteContact();
                }
                builder.setSingleChoiceItems(simpleAdapter, -1, new Dialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (service != null) {
                            try {
                                // 1 = PJSUA_XFER_NO_REQUIRE_REPLACES
                                service.xferReplace(call.getCallId(), remoteCalls.get(which).getCallId(), 1);
                            } catch (RemoteException e) {
                                Log.e(TAG, "Was not able to call service method", e);
                            }
                        }
                        dialog.dismiss();
                    }
                }).setCancelable(true).setNeutralButton(R.string.cancel, new Dialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
            }

            break;
        }
        case ADD_CALL: {
            Intent pickupIntent = new Intent(this, PickupSipUri.class);
            startActivityForResult(pickupIntent, PICKUP_SIP_URI_NEW_CALL);
            break;
        }
        case START_RECORDING: {
            if (service != null) {
                // TODO : add a tweaky setting for two channel recording in different files.
                // Would just result here in two calls to start recording with different bitmask
                service.startRecording(call.getCallId(), SipManager.BITMASK_ALL);
            }
            break;
        }
        case STOP_RECORDING: {
            if (service != null) {
                service.stopRecording(call.getCallId());
            }
            break;
        }
        case START_VIDEO:
        case STOP_VIDEO: {
            if (service != null) {
                Bundle opts = new Bundle();
                opts.putBoolean(SipCallSession.OPT_CALL_VIDEO, whichAction == START_VIDEO);
                service.updateCallOptions(call.getCallId(), opts);
            }
            break;
        }
        case ZRTP_TRUST: {
            if (service != null) {
                service.zrtpSASVerified(call.getCallId());
            }
            break;
        }
        case ZRTP_REVOKE: {
            if (service != null) {
                service.zrtpSASRevoke(call.getCallId());
            }
            break;
        }
        }
    } catch (RemoteException e) {
        Log.e(TAG, "Was not able to call service method", e);
    }
}