Harshith
Harshith

Reputation: 397

How to set multiple spans on a TextView's text (clickable and bold)

    mSpannableString = new SpannableString("12:00PM");

    mSpannableString.setSpan(clickableSpan, 0, 7, 0);
    mSpannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, 7, 0);

    TextView textView = new TextView(getContext());
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(mSpannableString);

    mCancelFrom.setText(getString(R.string.cancel_from_text) + " " + mSpannableString);

i need to set the text to bold and make it clickable. the above code i have written in a dialog. the string "12:00PM" is getting displayed. but there is not bold effect on it and it is not clickable. can you hel me with this?

Upvotes: 6

Views: 2875

Answers (2)

Siyamed
Siyamed

Reputation: 505

When you execute mCancelFrom.setText(getString(R.string.cancel_from_text) + " " + mSpannableString);

which executes: getString(R.string.cancel_from_text) + " " + mSpannableString

The result of the above operation is a "String" therefore framework calls mSpannableString.toString to be able to append the previous two strings and you lose your spans etc.

Something like this (this is almost exactly your code):

String tmp = getString(R.string.cancel_from_text) + " ";
mSpannableString = new SpannableString(tmp + "12:00PM");

mSpannableString.setSpan(clickableSpan, tmp.length(), mSpannableString.length(), 0);
mSpannableString.setSpan(new StyleSpan(Typeface.BOLD), tmp.length(), mSpannableString.length(), 0);

TextView textView = new TextView(getContext());
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(mSpannableString);

Upvotes: 0

Abhishek Patel
Abhishek Patel

Reputation: 4328

Try This ,it may be help to you

SpannableString ss = new SpannableString("12:00PM");
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            startActivity(new Intent(SendSMS.this, SendSMS.class));
        }
        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);
        }
    };
    ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(clickableSpan, 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    mCancelFrom.setText(getString(R.string.cancel_from_text) + " " + ss);

Upvotes: 7

Related Questions