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:piuk.blockchain.android.ui.dialogs.TransactionSummaryDialog.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);

    final FragmentActivity activity = getActivity();

    final LayoutInflater inflater = LayoutInflater.from(activity);

    final Builder dialog = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Theme_Dialog))
            .setTitle(R.string.transaction_summary_title);

    final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.transaction_summary_fragment, null);

    dialog.setView(view);//from  w w  w.  j av  a2  s .c  o  m

    try {
        final MyRemoteWallet wallet = application.getRemoteWallet();

        BigInteger totalOutputValue = BigInteger.ZERO;
        for (TransactionOutput output : tx.getOutputs()) {
            totalOutputValue = totalOutputValue.add(output.getValue());
        }

        final TextView resultDescriptionView = (TextView) view.findViewById(R.id.result_description);
        final TextView toView = (TextView) view.findViewById(R.id.transaction_to);
        final TextView toViewLabel = (TextView) view.findViewById(R.id.transaction_to_label);
        final View toViewContainer = (View) view.findViewById(R.id.transaction_to_container);
        final TextView hashView = (TextView) view.findViewById(R.id.transaction_hash);
        final TextView transactionTimeView = (TextView) view.findViewById(R.id.transaction_date);
        final TextView confirmationsView = (TextView) view.findViewById(R.id.transaction_confirmations);
        final TextView noteView = (TextView) view.findViewById(R.id.transaction_note);
        final Button addNoteButton = (Button) view.findViewById(R.id.add_note_button);
        final TextView feeView = (TextView) view.findViewById(R.id.transaction_fee);
        final View feeViewContainer = view.findViewById(R.id.transaction_fee_container);
        final TextView valueNowView = (TextView) view.findViewById(R.id.transaction_value);
        final View valueNowContainerView = view.findViewById(R.id.transaction_value_container);

        String to = null;
        for (TransactionOutput output : tx.getOutputs()) {
            try {
                String toAddress = output.getScriptPubKey().getToAddress().toString();
                if (!wallet.isAddressMine(toAddress)) {
                    to = toAddress;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String from = null;
        for (TransactionInput input : tx.getInputs()) {
            try {
                String fromAddress = input.getFromAddress().toString();
                if (!wallet.isAddressMine(fromAddress)) {
                    from = fromAddress;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        long realResult = 0;
        int confirmations = 0;

        if (tx instanceof MyTransaction) {
            MyTransaction myTx = (MyTransaction) tx;

            realResult = myTx.getResult().longValue();

            if (wallet.getLatestBlock() != null) {
                confirmations = wallet.getLatestBlock().getHeight() - myTx.getHeight() + 1;
            }

        } else if (application.isInP2PFallbackMode()) {
            realResult = tx.getValue(application.bitcoinjWallet).longValue();

            if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING)
                confirmations = tx.getConfidence().getDepthInBlocks();
        }

        final long finalResult = realResult;

        if (realResult <= 0) {
            toViewLabel.setText(R.string.transaction_fragment_to);

            if (to == null) {
                ((LinearLayout) toViewContainer.getParent()).removeView(toViewContainer);
            } else {
                toView.setText(to);
            }
        } else {
            toViewLabel.setText(R.string.transaction_fragment_from);

            if (from == null) {
                ((LinearLayout) toViewContainer.getParent()).removeView(toViewContainer);
            } else {
                toView.setText(from);
            }
        }

        //confirmations view
        if (confirmations > 0) {
            confirmationsView.setText("" + confirmations);
        } else {
            confirmationsView.setText("Unconfirmed");
        }

        //Hash String view
        final String hashString = new String(Hex.encode(tx.getHash().getBytes()), "UTF-8");

        hashView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("https:/" + Constants.BLOCKCHAIN_DOMAIN + "/tx/" + hashString));

                startActivity(browserIntent);
            }
        });

        //Notes View
        String note = wallet.getTxNotes().get(hashString);

        if (note == null) {
            addNoteButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();

                    AddNoteDialog.showDialog(getFragmentManager(), hashString);
                }
            });

            view.removeView(noteView);
        } else {
            view.removeView(addNoteButton);

            noteView.setText(note);

            noteView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();

                    AddNoteDialog.showDialog(getFragmentManager(), hashString);
                }
            });
        }

        addNoteButton.setEnabled(!application.isInP2PFallbackMode());

        SpannableString content = new SpannableString(hashString);
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        hashView.setText(content);

        if (realResult > 0 && from != null)
            resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_received,
                    WalletUtils.formatValue(BigInteger.valueOf(realResult))));
        else if (realResult < 0 && to != null)
            resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_sent,
                    WalletUtils.formatValue(BigInteger.valueOf(realResult))));
        else
            resultDescriptionView.setText(this.getString(R.string.transaction_fragment_amount_you_moved,
                    WalletUtils.formatValue(totalOutputValue)));

        final Date time = tx.getUpdateTime();

        transactionTimeView.setText(dateFormat.format(time));

        //These will be made visible again later once information is fetched from server
        feeViewContainer.setVisibility(View.GONE);
        valueNowContainerView.setVisibility(View.GONE);

        if (tx instanceof MyTransaction) {
            MyTransaction myTx = (MyTransaction) tx;

            final long txIndex = myTx.getTxIndex();

            final Handler handler = new Handler();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final JSONObject obj = getTransactionSummary(txIndex, wallet.getGUID(), finalResult);

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (obj.get("fee") != null) {
                                        feeViewContainer.setVisibility(View.VISIBLE);

                                        feeView.setText(WalletUtils.formatValue(
                                                BigInteger.valueOf(Long.valueOf(obj.get("fee").toString())))
                                                + " BTC");
                                    }

                                    if (obj.get("confirmations") != null) {
                                        int confirmations = ((Number) obj.get("confirmations")).intValue();

                                        confirmationsView.setText("" + confirmations);
                                    }

                                    String result_local = (String) obj.get("result_local");
                                    String result_local_historical = (String) obj
                                            .get("result_local_historical");

                                    if (result_local != null && result_local.length() > 0) {
                                        valueNowContainerView.setVisibility(View.VISIBLE);

                                        if (result_local_historical == null
                                                || result_local_historical.length() == 0
                                                || result_local_historical.equals(result_local)) {
                                            valueNowView.setText(result_local);
                                        } else {
                                            valueNowView.setText(getString(R.string.value_now_ten, result_local,
                                                    result_local_historical));
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Dialog d = dialog.create();

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

    lp.dimAmount = 0;
    lp.width = WindowManager.LayoutParams.FILL_PARENT;
    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

    d.show();

    d.getWindow().setAttributes(lp);

    d.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    return d;
}

From source file:android.support.v7.widget.SuggestionsAdapter.java

private CharSequence formatUrl(CharSequence url) {
    if (mUrlColor == null) {
        // Lazily get the URL color from the current theme.
        TypedValue colorValue = new TypedValue();
        mContext.getTheme().resolveAttribute(R.attr.textColorSearchUrl, colorValue, true);
        mUrlColor = mContext.getResources().getColorStateList(colorValue.resourceId);
    }//from  w  ww. ja v  a  2  s . c o m

    SpannableString text = new SpannableString(url);
    text.setSpan(new TextAppearanceSpan(null, 0, 0, mUrlColor, null), 0, url.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return text;
}

From source file:android.support.v7ox.widget.SuggestionsAdapter.java

private CharSequence formatUrl(CharSequence url) {
    if (mUrlColor == null) {
        // Lazily get the URL color from the current theme.
        TypedValue colorValue = new TypedValue();
        mContext.getTheme().resolveAttribute(R.attr.textColorSearchUrl_ox, colorValue, true);
        mUrlColor = mContext.getResources().getColorStateList(colorValue.resourceId);
    }// w  ww .  j  a v  a 2s .  co  m

    SpannableString text = new SpannableString(url);
    text.setSpan(new TextAppearanceSpan(null, 0, 0, mUrlColor, null), 0, url.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return text;
}

From source file:es.usc.citius.servando.calendula.activities.CalendarActivity.java

public CharSequence addPickupList(CharSequence msg, List<PickupInfo> pks) {

    Paint textPaint = new Paint();
    //obviously, we have to set textSize into Paint object
    textPaint.setTextSize(getResources().getDimensionPixelOffset(R.dimen.medium_font_size));
    Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();

    for (PickupInfo p : pks) {
        Patient patient = pickupUtils.getPatient(p);
        int color = patient.color();
        String str = "       " + p.medicine().name() + " (" + dtf2.format(p.from().toDate()) + " - "
                + dtf2.format(p.to().toDate()) + ")\n";
        Spannable text = new SpannableString(str);
        text.setSpan(new ForegroundColorSpan(color), 0, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        Drawable d = getResources().getDrawable(AvatarMgr.res(patient.avatar()));
        d.setBounds(0, 0, fontMetrics.bottom, fontMetrics.bottom);
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        text.setSpan(span, 0, 5, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        msg = TextUtils.concat(msg, text);
    }//  ww  w.ja  v  a 2  s.co  m
    return msg;
}

From source file:com.securecomcode.text.notifications.MessageNotifier.java

private static NotificationState constructNotificationState(Context context, MasterSecret masterSecret,
        Cursor cursor) {//w w  w . java  2 s. c  om
    NotificationState notificationState = new NotificationState();
    MessageRecord record;
    MmsSmsDatabase.Reader reader;

    if (masterSecret == null)
        reader = DatabaseFactory.getMmsSmsDatabase(context).readerFor(cursor);
    else
        reader = DatabaseFactory.getMmsSmsDatabase(context).readerFor(cursor, masterSecret);

    while ((record = reader.getNext()) != null) {
        Recipient recipient = record.getIndividualRecipient();
        Recipients recipients = record.getRecipients();
        long threadId = record.getThreadId();
        SpannableString body = record.getDisplayBody();
        Uri image = null;
        Recipients threadRecipients = null;

        if (threadId != -1) {
            threadRecipients = DatabaseFactory.getThreadDatabase(context).getRecipientsForThreadId(threadId);
        }

        // XXXX This is so fucked up.  FIX ME!
        if (body.toString().equals(context.getString(R.string.MessageDisplayHelper_decrypting_please_wait))) {
            body = new SpannableString(context.getString(R.string.MessageNotifier_encrypted_message));
            body.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, body.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        notificationState.addNotification(
                new NotificationItem(recipient, recipients, threadRecipients, threadId, body, image));
    }

    reader.close();
    return notificationState;
}

From source file:liqui.droid.activity.Base.java

/**
 * Creates the breadcrumb./*from ww w . ja va2 s  . c o m*/
 *
 * @param subTitle the sub title
 * @param breadCrumbHolders the bread crumb holders
 */
public void createBreadcrumb(String subTitle, BreadCrumbHolder... breadCrumbHolders) {
    if (breadCrumbHolders != null) {
        LinearLayout llPart = (LinearLayout) this.findViewById(R.id.ll_part);
        for (int i = 0; i < breadCrumbHolders.length; i++) {
            TextView tvBreadCrumb = new TextView(getApplication());
            SpannableString part = new SpannableString(breadCrumbHolders[i].getLabel());
            part.setSpan(new UnderlineSpan(), 0, part.length(), 0);
            tvBreadCrumb.append(part);
            tvBreadCrumb.setTag(breadCrumbHolders[i]);
            tvBreadCrumb.setBackgroundResource(R.drawable.default_link);
            tvBreadCrumb.setTextAppearance(getApplication(), R.style.default_text_small);
            tvBreadCrumb.setSingleLine(true);
            tvBreadCrumb.setOnClickListener(new OnClickBreadCrumb(this));

            llPart.addView(tvBreadCrumb);

            if (i < breadCrumbHolders.length - 1) {
                TextView slash = new TextView(getApplication());
                slash.setText(" / ");
                slash.setTextAppearance(getApplication(), R.style.default_text_small);
                llPart.addView(slash);
            }
        }
    }

    ScrollingTextView tvSubtitle = (ScrollingTextView) this.findViewById(R.id.tv_subtitle);
    tvSubtitle.setText(subTitle);
}

From source file:com.android.launcher3.allapps.FullMergeAlgorithm.java

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    // This is a focus listener that proxies focus from a view into the list view.  This is to
    // work around the search box from getting first focus and showing the cursor.
    getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override// w  w  w. j a  v a  2  s  .  c  o  m
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                mAppsRecyclerView.requestFocus();
            }
        }
    });

    mSearchContainer = findViewById(R.id.search_container);

    if (Utilities.isAllowNightModePrefEnabled(getContext())) {
        mSearchContainer.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.night_color));
    } else {
        if (Utilities.getDrawerBackgroundPrefEnabled(getContext()) != -1) {
            mSearchContainer.setBackgroundColor(Utilities.getDrawerBackgroundPrefEnabled(getContext()));
        } else {
            mSearchContainer.setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.white));
        }
    }
    mSearchInput = (ExtendedEditText) findViewById(R.id.search_box_input);

    // Update the hint to contain the icon.
    // Prefix the original hint with two spaces. The first space gets replaced by the icon
    // using span. The second space is used for a singe space character between the hint
    // and the icon.
    SpannableString spanned = new SpannableString("  " + mSearchInput.getHint());
    spanned.setSpan(new TintedDrawableSpan(getContext(), R.drawable.ic_allapps_search), 0, 1,
            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
    mSearchInput.setHint(spanned);

    mSearchContainerOffsetTop = getResources().getDimensionPixelSize(R.dimen.all_apps_search_bar_margin_top);

    mElevationController = Utilities.ATLEAST_LOLLIPOP
            ? new HeaderElevationController.ControllerVL(mSearchContainer)
            : new HeaderElevationController.ControllerV16(mSearchContainer);

    // Load the all apps recycler view
    mAppsRecyclerView = (AllAppsRecyclerView) findViewById(R.id.apps_list_view);
    mAppsRecyclerView.setApps(mApps);
    mAppsRecyclerView.setLayoutManager(mLayoutManager);
    mAppsRecyclerView.setAdapter(mAdapter);
    mAppsRecyclerView.setHasFixedSize(true);
    mAppsRecyclerView.addOnScrollListener(mElevationController);
    mAppsRecyclerView.setElevationController(mElevationController);

    if (mItemDecoration != null) {
        mAppsRecyclerView.addItemDecoration(mItemDecoration);
    }

    FocusedItemDecorator focusedItemDecorator = new FocusedItemDecorator(mAppsRecyclerView);
    mAppsRecyclerView.addItemDecoration(focusedItemDecorator);
    mAppsRecyclerView.preMeasureViews(mAdapter);
    mAdapter.setIconFocusListener(focusedItemDecorator.getFocusListener());

    if (FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP) {
        getRevealView().setVisibility(View.VISIBLE);
        getContentView().setVisibility(View.VISIBLE);
        getContentView().setBackground(null);
    }
}

From source file:im.vector.notifications.NotificationUtils.java

/**
 * Add a text style to a notification when there are several notified rooms.
 *
 * @param context            the context
 * @param builder            the notification builder
 * @param roomsNotifications the rooms notifications
 *///from w  w w.  ja v  a2s . c o  m
private static void addTextStyleWithSeveralRooms(Context context, NotificationCompat.Builder builder,
        RoomsNotifications roomsNotifications) {
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    for (RoomNotifications roomNotifications : roomsNotifications.mRoomNotifications) {
        SpannableString notifiedLine = new SpannableString(roomNotifications.mMessagesSummary);
        notifiedLine.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
                roomNotifications.mMessageHeader.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        inboxStyle.addLine(notifiedLine);
    }

    inboxStyle.setBigContentTitle(context.getString(R.string.riot_app_name));
    inboxStyle.setSummaryText(roomsNotifications.mSummaryText);
    builder.setStyle(inboxStyle);

    TaskStackBuilder stackBuilderTap = TaskStackBuilder.create(context);
    Intent roomIntentTap;

    // add the home page the activity stack
    stackBuilderTap.addNextIntentWithParentStack(new Intent(context, VectorHomeActivity.class));

    if (roomsNotifications.mIsInvitationEvent) {
        // for invitation the room preview must be displayed
        roomIntentTap = CommonActivityUtils.buildIntentPreviewRoom(roomsNotifications.mSessionId,
                roomsNotifications.mRoomId, context, VectorFakeRoomPreviewActivity.class);
    } else {
        roomIntentTap = new Intent(context, VectorRoomActivity.class);
        roomIntentTap.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomsNotifications.mRoomId);
    }

    // the action must be unique else the parameters are ignored
    roomIntentTap.setAction(TAP_TO_VIEW_ACTION + ((int) (System.currentTimeMillis())));
    stackBuilderTap.addNextIntent(roomIntentTap);
    builder.setContentIntent(stackBuilderTap.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

    // offer to open the rooms list
    {
        Intent openIntentTap = new Intent(context, VectorHomeActivity.class);

        // Recreate the back stack
        TaskStackBuilder viewAllTask = TaskStackBuilder.create(context).addNextIntent(openIntentTap);

        builder.addAction(R.drawable.ic_home_black_24dp, context.getString(R.string.bottom_action_home),
                viewAllTask.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
    }
}

From source file:com.sahildave.snackbar.SnackBar.java

private CharSequence getBulletSpanMessage(String[] subMessageArray) {
    CharSequence subMessage = "";
    for (String subMessageItem : subMessageArray) {

        SpannableString spannableString = new SpannableString(subMessageItem + "\n");
        spannableString.setSpan(new BulletSpan(15), 0, subMessageItem.length(), 0);

        subMessage = TextUtils.concat(subMessage, spannableString);
    }//  ww w . ja v a 2 s .c o  m
    return subMessage;
}

From source file:org.catrobat.catroid.ui.fragment.BackPackSoundFragment.java

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

    if (numberOfSelectedItems == 0) {
        actionMode.setTitle(actionModeTitle);
    } else {/*ww  w  .j  a  va 2 s .  c  o  m*/
        String appendix = multipleItemAppendixDeleteActionMode;

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

        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(R.color.actionbar_title_color)),
                titleLength + 1, titleLength + (1 + numberOfItems.length()),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        actionMode.setTitle(completeSpannedTitle);
    }
}