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:org.awesomeapp.messenger.ui.MessageListItem.java

public void bindIncomingMessage(MessageViewHolder holder, int id, int messageType, String address,
        String nickname, final String mimeType, final String body, Date date, Markup smileyRes,
        boolean scrolling, EncryptionState encryption, boolean showContact, int presenceStatus) {

    mHolder = holder;/*from www .  j a  v  a  2s  .  c  o  m*/
    applyStyleColors();
    mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);
    mHolder.mAudioContainer.setVisibility(View.GONE);
    mHolder.mMediaContainer.setVisibility(View.GONE);

    if (nickname == null)
        nickname = address;

    lastMessage = formatMessage(body);
    showAvatar(address, nickname, true, presenceStatus);

    mHolder.resetOnClickListenerMediaThumbnail();

    if (mimeType != null) {

        Uri mediaUri = Uri.parse(body);
        lastMessage = "";

        if (mimeType.startsWith("audio")) {
            mHolder.mAudioButton.setImageResource(R.drawable.media_audio_play);

            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);

            showMediaThumbnail(mimeType, mediaUri, id, mHolder);

            mHolder.mMediaContainer.setVisibility(View.VISIBLE);

        }

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

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

            String mimeTypeSticker = "image/png";

            try {

                String assetPath = cmds[1].split(" ")[0].toLowerCase();//just get up to any whitespace;

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

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

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                Log.e(ImApp.LOG_TAG, "error loading sticker bitmap: " + cmds[1], 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 {
            mHolder.mContainer.setBackgroundResource(android.R.color.transparent);
            lastMessage = "";
        }

    }

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

    if (lastMessage.length() > 0) {
        mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
    } else {
        mHolder.mTextViewForMessages.setText(lastMessage);
    }

    if (date != null) {

        String contact = null;
        if (showContact) {
            String[] nickParts = nickname.split("/");
            contact = nickParts[nickParts.length - 1];
        }

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

        mHolder.mTextViewForTimestamp.setText(tsText);
        mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);

    } else {

        mHolder.mTextViewForTimestamp.setText("");
        //mHolder.mTextViewForTimestamp.setVisibility(View.GONE);

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

From source file:com.handpoint.headstart.client.ui.ReceiptActivity.java

/** Called when the activity is first created. */
@Override//  www.j  a  v a 2  s .c o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.receipt);

    long transactionId = getIntent().getLongExtra(EXTRA_TRANSACTION_ID, -1);
    if (transactionId == -1) {
        finish();
        return;
    }

    DaoHelper daoHelper = new DaoHelper(this);
    daoHelper.open(false);
    mResult = daoHelper.getFinancialTransaction(transactionId);
    Basket basket = daoHelper.getBasketByTransaction(transactionId);
    if (null != basket) {
        mBasketItem = daoHelper.getBasketItem(basket.getId());
    }
    daoHelper.close();
    Button buttonDone = (Button) findViewById(R.id.bottom_button);
    buttonDone.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            finish();
        }
    });

    mRevertButton = (Button) findViewById(R.id.revert_button);
    if ((mResult.getType() == FinancialTransactionResult.FT_TYPE_SALE
            || mResult.getType() == FinancialTransactionResult.FT_TYPE_REFUND)
            && null != mResult.getTransactionId() && mResult.getTransactionId().length() > 0
            && mResult.getTransactionStatus() == TransactionStatus.EFT_TRANSACTION_APPROVED
            && 0 == mResult.getVoidedId()) {
        mRevertButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent startVoidIntent = new Intent(HeadstartService.ACTION_MAIN);
                startVoidIntent.putExtra(HeadstartService.EXTRA_OPERATION_TYPE,
                        mResult.getType() == FinancialTransactionResult.FT_TYPE_SALE
                                ? FinancialTransactionResult.FT_TYPE_SALE_VOID
                                : FinancialTransactionResult.FT_TYPE_REFUND_VOID);
                startVoidIntent.putExtra(HeadstartService.EXTRA_PAYMENT_VALUE, mResult.getAuthorizedAmount());
                startVoidIntent.putExtra(HeadstartService.EXTRA_PAYMENT_CURRENCY, mResult.getCurrency());
                startVoidIntent.putExtra(HeadstartService.EXTRA_PAYMENT_TRANSACTION_ID,
                        mResult.getTransactionId());
                startVoidIntent.putExtra("com.handpoint.headstart.client.VOIDED_ID", mResult.getId());
                startActivity(startVoidIntent);
                finish();
            }
        });
    } else {
        mRevertButton.setVisibility(View.GONE);
    }

    mDetailsButton = (Button) findViewById(R.id.details_button);
    if (!TextUtils.isEmpty(mResult.getMerchantReceipt()) || !TextUtils.isEmpty(mResult.getCustomerReceipt())) {
        mDetailsButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ReceiptActivity.this, RawReceiptActivity.class);
                intent.putExtra("merchantReceipt", mResult.getMerchantReceipt());
                intent.putExtra("customerReceipt", mResult.getCustomerReceipt());
                intent.putExtra("signatureVerificationText", mResult.getSignatureVerificationText());
                intent.putExtra("signatureImage", mResult.getSignaturePath());
                startActivity(intent);
            }
        });
    } else {
        mDetailsButton.setVisibility(View.GONE);
    }

    initReceiptView();

    final ImageView sendEmailView = (ImageView) findViewById(R.id.email_send_image);
    mEmailView = (EditText) findViewById(R.id.email_address);

    final ImageView sendSmsView = (ImageView) findViewById(R.id.sms_send_image);
    mSmsView = (EditText) findViewById(R.id.sms_address);

    sendEmailView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            hideSoftKeyboard(mEmailView);
            mPdfDlg = new ProgressDialog(v.getContext());
            mPdfDlg.setMessage(getString(R.string.pdf_dlg_msg));
            mPdfDlg.setTitle(getString(R.string.pdf_dlg_title));
            mPdfDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mPdfDlg.setCancelable(true);
            mPdfDlg.show();

            new Thread(new Runnable() {
                public void run() {
                    ArrayList<File> attachments = null;
                    try {
                        Thread.sleep(1000);
                        attachments = getCustomerEmailAttachments();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (attachments != null) {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        mPdfDlg.dismiss();

                        SenderHelper.MerchantEmailServerSettings serverSettings = new SenderHelper.MerchantEmailServerSettings(
                                ReceiptActivity.this);
                        SendAsyncTask sendTask = new SendAsyncTask();
                        sendTask.execute(new EmailDataHolder(ReceiptActivity.this, serverSettings,
                                mEmailView.getText().toString(), new SpannableString(""), attachments,
                                EmailTypes.CUSTOMER));
                    }
                }
            }).start();
        }
    });

    sendSmsView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            hideSoftKeyboard(mSmsView);
            SenderHelper.sendReceiptSms(ReceiptActivity.this, mSmsView.getText().toString(), mResult);
            //mark customer receipt as "copy"
            markCustomerReceiptAsCopied(ReceiptActivity.this, mResult);
        }
    });

    if (getIntent().getBooleanExtra(EXTRA_SEND_MERCHANT_RECEIPT, false) && savedInstanceState == null) {
        sendMerchantReceipt();
    }

    // repeat image bug fix
    //      View background = findViewById(R.id.rootLayout);
    //      ((BitmapDrawable)background.getBackground()).setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);

    //      getSupportActionBar().setTitle(R.string.abs_title);
    //      getSupportActionBar().setDisplayHomeAsUpEnabled(true);

}

From source file:eu.power_switch.widget.activity.ConfigureReceiverWidgetActivity.java

private void saveCurrentConfiguration() {
    try {/*  w  w  w  .j  a  v a2s.  c  o m*/
        // First, get the App Widget ID from the Intent that launched the Activity:
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
            int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            // Perform your App Widget configuration:
            Apartment selectedApartment = getSelectedApartment();
            Room selectedRoom = selectedApartment.getRoom(spinnerRoom.getSelectedItem().toString());
            Receiver selectedReceiver = selectedRoom.getReceiver(spinnerReceiver.getSelectedItem().toString());

            // save new widget data to database
            ReceiverWidget receiverWidget = new ReceiverWidget(appWidgetId, selectedRoom.getId(),
                    selectedReceiver.getId());
            DatabaseHandler.addReceiverWidget(receiverWidget);
            // When the configuration is complete, get an instance of
            // the AppWidgetManager by calling getInstance(Context):
            AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(ConfigureReceiverWidgetActivity.this);
            // Update the App Widget with a RemoteViews layout by
            // calling updateAppWidget(int, RemoteViews):
            RemoteViews remoteViews = new RemoteViews(getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
                    R.layout.widget_receiver);

            LinkedList<Button> buttons = selectedReceiver.getButtons();

            remoteViews.setTextViewText(R.id.textView_receiver_widget_name, selectedApartment.getName() + ": "
                    + selectedRoom.getName() + ": " + selectedReceiver.getName());

            int buttonOffset = 0;
            for (Button button : buttons) {
                // set button action
                RemoteViews buttonView = new RemoteViews(
                        getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
                        R.layout.widget_receiver_button_layout);
                SpannableString s = new SpannableString(button.getName());
                s.setSpan(new StyleSpan(Typeface.BOLD), 0, button.getName().length(), 0);
                buttonView.setTextViewText(R.id.button_widget_universal, s);

                if (SmartphonePreferencesHandler.getHighlightLastActivatedButton()
                        && selectedReceiver.getLastActivatedButtonId().equals(button.getId())) {
                    buttonView.setTextColor(R.id.button_widget_universal,
                            ContextCompat.getColor(getApplicationContext(), R.color.color_light_blue_a700));
                }

                PendingIntent pendingIntent = WidgetIntentReceiver.buildReceiverWidgetActionPendingIntent(
                        getApplicationContext(), selectedApartment, selectedRoom, selectedReceiver, button,
                        appWidgetId * 15 + buttonOffset);

                buttonView.setOnClickPendingIntent(R.id.button_widget_universal, pendingIntent);

                remoteViews.addView(R.id.linearlayout_receiver_widget, buttonView);
                buttonOffset++;
            }

            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

            // Finally, create the return Intent, set it with the
            // Activity result, and finish the Activity:
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            setResult(RESULT_OK, resultValue);
            finish();
        }
    } catch (Exception e) {
        StatusMessageHandler.showErrorMessage(this, e);
    }
}

From source file:edu.berkeley.boinc.ProjectDetailsFragment.java

private void populateLayout() {

    if (project == null) {
        retryLayout = true;/*from  ww  w.ja v  a2 s .c  om*/
        return; // if data not available yet, return. frequently retrys with onReceive
    }

    retryLayout = false;
    View v = root;

    updateChangingItems(v);

    slideshowWrapper = (HorizontalScrollView) v.findViewById(R.id.slideshow_wrapper);
    slideshowHook = (LinearLayout) v.findViewById(R.id.slideshow_hook);
    slideshowLoading = (ProgressBar) v.findViewById(R.id.slideshow_loading);

    // set website
    TextView website = (TextView) v.findViewById(R.id.project_url);
    SpannableString content = new SpannableString(project.master_url);
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    website.setText(content);
    website.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(project.master_url));
            startActivity(i);
        }
    });

    // set general area
    if (projectInfo != null && projectInfo.generalArea != null) {
        TextView generalArea = (TextView) v.findViewById(R.id.general_area);
        generalArea.setText(projectInfo.generalArea);
    } else {
        LinearLayout wrapper = (LinearLayout) v.findViewById(R.id.general_area_wrapper);
        wrapper.setVisibility(View.GONE);
    }

    // set specific area
    if (projectInfo != null && projectInfo.specificArea != null) {
        TextView specificArea = (TextView) v.findViewById(R.id.specific_area);
        specificArea.setText(projectInfo.specificArea);
    } else {
        LinearLayout wrapper = (LinearLayout) v.findViewById(R.id.specific_area_wrapper);
        wrapper.setVisibility(View.GONE);
    }

    // set description
    if (projectInfo != null && projectInfo.description != null) {
        TextView description = (TextView) v.findViewById(R.id.description);
        description.setText(projectInfo.description);
    } else {
        LinearLayout wrapper = (LinearLayout) v.findViewById(R.id.description_wrapper);
        wrapper.setVisibility(View.GONE);
    }

    // set home
    if (projectInfo != null && projectInfo.home != null) {
        TextView home = (TextView) v.findViewById(R.id.based_at);
        home.setText(projectInfo.home);
    } else {
        LinearLayout wrapper = (LinearLayout) v.findViewById(R.id.based_at_wrapper);
        wrapper.setVisibility(View.GONE);
    }

    // load slideshow
    new UpdateSlideshowImagesAsync().execute();
}

From source file:com.money.manager.ex.core.Core.java

/**
 * This method allows to highlight in bold the content of a search string
 * @param search       string/*from  w w  w.  j  a  v  a 2s .  com*/
 * @param originalText string where to find
 * @return CharSequence modified
 */
public CharSequence highlight(String search, String originalText) {
    if (TextUtils.isEmpty(search))
        return originalText;
    // ignore case and accents
    // the same thing should have been done for the search text
    String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();

    int start = normalizedText.indexOf(search.toLowerCase());
    if (start < 0) {
        // not found, nothing to to
        return originalText;
    } else {
        // highlight each appearance in the original text
        // while searching in normalized text
        Spannable highlighted = new SpannableString(originalText);
        while (start >= 0) {
            int spanStart = Math.min(start, originalText.length());
            int spanEnd = Math.min(start + search.length(), originalText.length());

            highlighted.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanStart, spanEnd,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            start = normalizedText.indexOf(search, spanEnd);
        }
        return highlighted;
    }
}

From source file:com.brq.wallet.activity.modern.ModernMain.java

private void checkGapBug() {
    final WalletManager walletManager = _mbwManager.getWalletManager(false);
    final List<Integer> gaps = walletManager.getGapsBug();
    if (!gaps.isEmpty()) {
        try {/* w  w w. ja va  2s.  c o m*/
            final List<Address> gapAddresses = walletManager.getGapAddresses(AesKeyCipher.defaultKeyCipher());
            final String gapsString = Joiner.on(", ").join(gapAddresses);
            Log.d("Gaps", gapsString);

            final SpannableString s = new SpannableString(
                    "Sorry to interrupt you... \n \nWe discovered a bug in the account logic that will make problems if you someday need to restore from your 12 word backup.\n\nFor further information see here: https://wallet.mycelium.com/info/gaps \n\nMay we try to resolve it for you? Press OK, to share one address per affected account with us.");
            Linkify.addLinks(s, Linkify.ALL);

            final AlertDialog d = new AlertDialog.Builder(this).setTitle("Account Gap").setMessage(s)

                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            createPlaceHolderAccounts(gaps);
                            _mbwManager.reportIgnoredException(
                                    new RuntimeException("Address gaps: " + gapsString));
                        }
                    }).setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).show();

            // Make the textview clickable. Must be called after show()
            ((TextView) d.findViewById(android.R.id.message))
                    .setMovementMethod(LinkMovementMethod.getInstance());

        } catch (KeyCipher.InvalidKeyCipher invalidKeyCipher) {
            throw new RuntimeException(invalidKeyCipher);
        }
    }
}

From source file:com.abcvoipsip.ui.prefs.CodecsFragment.java

@Override
@SuppressWarnings("unchecked")
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info;
    try {/*from www .  ja  v  a2  s.  c  o  m*/
        info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    } catch (ClassCastException e) {
        Log.e(THIS_FILE, "bad menuInfo", e);
        return false;
    }

    HashMap<String, Object> codec = null;
    codec = (HashMap<String, Object>) mAdapter.getItem(info.position);

    if (codec == null) {
        // If for some reason the requested item isn't available, do nothing
        return false;
    }
    int selId = item.getItemId();
    if (selId == MENU_ITEM_ACTIVATE) {
        boolean isDisabled = ((Short) codec.get(CODEC_PRIORITY) == 0);
        final short newPrio = isDisabled ? (short) 1 : (short) 0;
        if (NON_FREE_CODECS.containsKey(codec.get(CODEC_ID)) && isDisabled) {
            final HashMap<String, Object> fCodec = codec;

            final TextView message = new TextView(getActivity());
            final SpannableString s = new SpannableString(
                    getString(R.string.this_codec_is_not_free) + NON_FREE_CODECS.get(codec.get(CODEC_ID)));
            Linkify.addLinks(s, Linkify.WEB_URLS);
            message.setText(s);
            message.setMovementMethod(LinkMovementMethod.getInstance());
            message.setPadding(10, 10, 10, 10);

            //Alert user that we will disable for all incoming calls as he want to quit
            new AlertDialog.Builder(getActivity()).setTitle(R.string.warning).setView(message)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            setCodecActivated(fCodec, newPrio);
                        }
                    }).setNegativeButton(R.string.cancel, null).show();
        } else {
            setCodecActivated(codec, newPrio);
        }
        return true;
    }
    return false;
}

From source file:fr.tvbarthel.attempt.googlyzooapp.MainActivity.java

@Override
public void onNavigationDrawerItemSelected(GooglyPetEntry petSelected) {
    final int googlyName = petSelected.getName();
    mSelectedGooglyPet = petSelected.getPetId();

    final String petName = getResources().getString(googlyName);
    final String oogly = getResources().getString(R.string.googly_name_ext);
    mTitle = new SpannableString(getResources().getString(googlyName) + oogly);
    mTitle.setSpan(new StyleSpan(Typeface.BOLD), 0, petName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    mTitle.setSpan(new TypefaceSpan("sans-serif-light"), petName.length() - 1, mTitle.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    mActionBarIcon = petSelected.getBlackAndWhiteIcon();

    if (mPetTrackerFragment != null) {
        mPetTrackerFragment.setGooglyPet(mSelectedGooglyPet);
    }// w ww . j  a  v  a 2s .c  o m
}

From source file:com.easemob.chatuidemo.activity.GroupPickContactsActivity.java

private void setSelectedNumber(int number) {
    String numberStr = number + "";
    SpannableString spannableString = new SpannableString(
            String.format(getString(R.string.filter_selected), number));
    spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_blue)), 2,
            2 + numberStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    selectedNumberTextView.setText(spannableString);
}

From source file:com.coinblesk.client.utils.UIUtils.java

public static SpannableString toSmallSpannable(String amount, String currency) {
    StringBuffer stringBuffer = new StringBuffer(amount + " " + currency);
    return new SpannableString(stringBuffer);
}