Example usage for android.text SpannableString SpannableString

List of usage examples for android.text SpannableString SpannableString

Introduction

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

Prototype

public SpannableString(CharSequence source) 

Source Link

Document

For the backward compatibility reasons, this constructor copies all spans including android.text.NoCopySpan .

Usage

From source file:de.spiritcroc.modular_remote.Util.java

public static Spannable getContainerContentReadableName(Container container, @Nullable String prefix) {
    if (prefix == null) {
        prefix = "";
    }/*from www.j  a  v a 2s.  c o m*/
    if (container.isEmpty()) {
        return new SpannableString(prefix + container.getReadableName());
    } else {
        ModuleFragment[] fragments = container.getFragments();
        String name = prefix + container.getReadableName();
        int spanStartIndex = name.length();
        name += " [" + fragments[0].getReadableName();
        int contentColor = fragments[0].getActivity().getResources().getColor(R.color.text_container_content);
        for (int i = 1; i < fragments.length; i++) {
            name += "; " + fragments[i].getReadableName();
        }
        name += "]";
        Spannable nameSpan = new SpannableString(name);
        nameSpan.setSpan(new ForegroundColorSpan(contentColor), spanStartIndex, name.length(),
                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return nameSpan;
    }
}

From source file:com.air.mobilebrowser.BrowserActivity.java

/** Logs an onscreen message for debugging. */
public void logMessage(final TextView consoleView, String message, String value, int color) {
    if (mIsDebugEnabled && consoleView != null) {
        consoleView.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override//w  w w .  j  av  a2  s. c  o m
            public void onFocusChange(View v, boolean hasFocus) {

                ViewParent parent = consoleView.getParent();
                final ScrollView scroll = (ScrollView) parent;

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {

                        scroll.smoothScrollTo(0, consoleView.getMeasuredHeight() + 10);

                    }
                }, 0);

            }
        });
        Editable editable = consoleView.getEditableText();

        SpannableString str = null;

        if (editable == null) {
            editable = new SpannableStringBuilder();
            str = new SpannableString(message + ": " + value);
            str.setSpan(new ForegroundColorSpan(color), message.length() + 2,
                    message.length() + 2 + value.length(), 0);
        } else {
            str = new SpannableString("\n" + message + ": " + value);
            str.setSpan(new ForegroundColorSpan(color), message.length() + 2,
                    message.length() + 3 + value.length(), 0);
        }

        editable.append(str);

        consoleView.setText(editable, TextView.BufferType.EDITABLE);

        ViewParent parent = consoleView.getParent();
        if (parent instanceof ScrollView) {
            final ScrollView scroll = (ScrollView) parent;

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    scroll.smoothScrollTo(0, consoleView.getMeasuredHeight() + 10);

                }
            }, 1000);
        }
    }
}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

private CharSequence generateFastForwardOrRewindTxt(long changingTime) {

    long duration = player == null ? 0 : player.getDuration();
    String result = stringForTime(changingTime) + " / " + stringForTime(duration);

    int index = result.indexOf("/");

    SpannableString spannableString = new SpannableString(result);

    TypedValue typedValue = new TypedValue();
    TypedArray a = getContext().obtainStyledAttributes(typedValue.data, new int[] { R.attr.colorAccent });
    int color = a.getColor(0, 0);
    a.recycle();/*  w ww. j av  a 2  s.c  o m*/
    spannableString.setSpan(new ForegroundColorSpan(color), 0, index, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    return spannableString;
}

From source file:hku.fyp14017.blencode.ui.fragment.LookFragment.java

private void updateActionModeTitle() {
    int numberOfSelectedItems = adapter.getAmountOfCheckedItems();

    if (numberOfSelectedItems == 0) {
        actionMode.setTitle(actionModeTitle);
    } else {/*from   ww  w .  ja v  a  2  s.co  m*/
        String appendix = multipleItemAppendixActionMode;

        if (numberOfSelectedItems == 1) {
            appendix = singleItemAppendixActionMode;
        }

        String numberOfItems = Integer.toString(numberOfSelectedItems);
        String completeTitle = actionModeTitle + " " + numberOfItems + " " + appendix;

        int titleLength = actionModeTitle.length();

        Spannable completeSpannedTitle = new SpannableString(completeTitle);
        completeSpannedTitle.setSpan(
                new ForegroundColorSpan(
                        getResources().getColor(hku.fyp14017.blencode.R.color.actionbar_title_color)),
                titleLength + 1, titleLength + (1 + numberOfItems.length()),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        actionMode.setTitle(completeSpannedTitle);
    }
}

From source file:com.lloydtorres.stately.helpers.SparkleHelper.java

/**
 * Stylify text view to primary colour and no underline
 * @param c App context//  ww w . j  av a 2s.  com
 * @param t TextView
 */
public static void styleLinkifiedTextView(Context c, TextView t) {
    // Get individual spans and replace them with clickable ones.
    Spannable s = new SpannableString(t.getText());
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for (URLSpan span : spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);
        span = new URLSpanNoUnderline(c, span.getURL());
        s.setSpan(span, start, end, 0);
    }

    t.setText(s);
    // Need to set this to allow for clickable TextView links.
    if (!(t instanceof HtmlTextView)) {
        t.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

From source file:com.kyakujin.android.autoeco.ui.MainActivity.java

/**
 * About//w w  w .ja  v a  2s  .c  o m
 */
private void showAboutDialog() {
    PackageManager pm = this.getPackageManager();
    String packageName = this.getPackageName();
    String versionName;
    try {
        PackageInfo info = pm.getPackageInfo(packageName, 0);
        versionName = info.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        versionName = "N/A";
    }

    SpannableStringBuilder aboutBody = new SpannableStringBuilder();

    SpannableString mailAddress = new SpannableString(getString(R.string.mailto));
    mailAddress.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse(getString(R.string.description_mailto)));
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.description_mail_subject));
            startActivity(intent);
        }
    }, 0, mailAddress.length(), 0);

    aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
    aboutBody.append("\n");
    aboutBody.append(mailAddress);

    LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.fragment_about_dialog, null);
    aboutBodyView.setText(aboutBody);
    aboutBodyView.setMovementMethod(LinkMovementMethod.getInstance());

    AlertDialog dlg = new AlertDialog.Builder(this).setTitle(R.string.alert_title_about).setView(aboutBodyView)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create();
    dlg.show();
}

From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    MenuItem item = menu.add(Menu.NONE, ACTIONBAR_MENU_ITEM_FIILTER, Menu.NONE,
            getString(R.string.order_call_taxi_page_title));
    SpannableString spanString = new SpannableString(item.getTitle().toString());
    spanString.setSpan(new ForegroundColorSpan(Color.WHITE), 0, spanString.length(), 0); //fix the color to white
    item.setTitle(spanString);/*from  w w  w .jav a 2  s.  c  o  m*/
    if (isShowOneKey)
        item.setVisible(true);
    else
        item.setVisible(false);
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    super.onCreateOptionsMenu(menu, inflater);
}

From source file:pl.motyczko.scrollheader.PagerSlidingTabStrip.java

private void updateActionBar() {
    float fraction = Math.abs(getTranslationY() / getAllowedVerticalScrollLength());
    if (mSpannableString == null)
        mSpannableString = new SpannableString(mActionBar.getTitle());
    mAlphaForegroundColorSpan.setAlpha(mActionBarTitleInterpolator.getInterpolation(fraction));
    mSpannableString.setSpan(mAlphaForegroundColorSpan, 0, mSpannableString.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    mActionBar.setTitle(mSpannableString);
}

From source file:com.hippo.nimingban.ui.ListActivity.java

private Spanned fixURLSpan(Spanned spanned) {
    Spannable spannable;//from  www. j ava  2  s. c om
    if (spanned instanceof Spannable) {
        spannable = (Spannable) spanned;
    } else {
        spannable = new SpannableString(spanned);
    }

    URLSpan[] urlSpans = spannable.getSpans(0, spanned.length(), URLSpan.class);
    if (urlSpans == null) {
        return spanned;
    }

    for (URLSpan urlSpan : urlSpans) {
        String url = urlSpan.getURL();
        if (TextUtils.isEmpty(url)) {
            spannable.removeSpan(urlSpan);
        }

        try {
            new URL(url);
        } catch (MalformedURLException e) {
            URL absoluteUrl;
            // It might be relative path
            try {
                // Use absolute url
                absoluteUrl = new URL(new URL(ACUrl.HOST), url);
                int start = spannable.getSpanStart(urlSpan);
                int end = spannable.getSpanEnd(urlSpan);
                spannable.removeSpan(urlSpan);
                spannable.setSpan(new URLSpan(absoluteUrl.toString()), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } catch (MalformedURLException e1) {
                // Can't get url
                spannable.removeSpan(urlSpan);
            }
        }
    }

    return spannable;
}

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

public void bindOutgoingMessage(MessageViewHolder holder, int id, int messageType, String address,
        final String mimeType, final String body, Date date, Markup smileyRes, boolean scrolling,
        DeliveryState delivery, EncryptionState encryption) {

    mHolder = holder;/*from   w ww . jav a  2  s  .c om*/
    applyStyleColors();

    mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);
    mHolder.mAudioContainer.setVisibility(View.GONE);
    mHolder.mMediaContainer.setVisibility(View.GONE);
    mHolder.mAudioButton.setImageResource(R.drawable.media_audio_play);

    mHolder.resetOnClickListenerMediaThumbnail();

    lastMessage = body;

    if (mimeType != null) {

        lastMessage = "";

        Uri mediaUri = Uri.parse(body);

        if (mimeType.startsWith("audio")) {
            try {
                mHolder.mAudioContainer.setVisibility(View.VISIBLE);
                showAudioPlayer(mimeType, mediaUri, id, mHolder);
            } catch (Exception e) {
                mHolder.mAudioContainer.setVisibility(View.GONE);
            }

        } else {
            mHolder.mTextViewForMessages.setVisibility(View.GONE);

            mHolder.mMediaContainer.setVisibility(View.VISIBLE);
            showMediaThumbnail(mimeType, mediaUri, id, mHolder);

        }

    } else if ((!TextUtils.isEmpty(lastMessage))
            && (lastMessage.charAt(0) == '/' || lastMessage.charAt(0) == ':')) {
        //            String cmd = lastMessage.toString().substring(1);
        boolean cmdSuccess = false;

        if (lastMessage.startsWith("/sticker:")) {
            String[] cmds = lastMessage.split(":");

            String mimeTypeSticker = "image/png";
            try {
                //make sure sticker exists
                AssetFileDescriptor afd = getContext().getAssets().openFd(cmds[1]);
                afd.getLength();
                afd.close();

                //now setup the new URI for loading local sticker asset
                Uri mediaUri = Uri.parse("asset://localhost/" + cmds[1].toLowerCase());

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                cmdSuccess = false;
            }

        } else if (lastMessage.startsWith(":")) {
            String[] cmds = lastMessage.split(":");

            String mimeTypeSticker = "image/png";
            try {
                String[] stickerParts = cmds[1].split("-");
                String stickerPath = "stickers/" + stickerParts[0].toLowerCase() + "/"
                        + stickerParts[1].toLowerCase() + ".png";

                //make sure sticker exists
                AssetFileDescriptor afd = getContext().getAssets().openFd(stickerPath);
                afd.getLength();
                afd.close();

                //now setup the new URI for loading local sticker asset
                Uri mediaUri = Uri.parse("asset://localhost/" + stickerPath);

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                cmdSuccess = false;
            }
        }

        if (!cmdSuccess) {
            mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
        } else {
            holder.mContainer.setBackgroundResource(android.R.color.transparent);
            lastMessage = "";
        }

    } else {
        mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
    }

    //if (isSelected())
    //  mHolder.mContainer.setBackgroundColor(getResources().getColor(R.color.holo_blue_bright));

    if (date != null) {

        CharSequence tsText = formatTimeStamp(date, messageType, delivery, encryption, null);

        mHolder.mTextViewForTimestamp.setText(tsText);

        mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);

    } else {
        mHolder.mTextViewForTimestamp.setText("");

    }
    if (linkify)
        LinkifyHelper.addLinks(mHolder.mTextViewForMessages, new URLSpanConverter());
    LinkifyHelper.addTorSafeLinks(mHolder.mTextViewForMessages);
}