Kyle
Kyle

Reputation: 725

How to set Spannable to TextView?

I have a TextView declared as follows..

<TextView
    android:id="@+id/cc_journal_survey_next_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:text="Next Survey: %s"/>

As you can see, Next Survey is bold and I want the string after it to not be bold. I am attempting to use a spannable as follows..

mNextTv = findViewById(R.id.cc_journal_survey_next_tv);

final SpannableString surveyName = new SpannableString(survey.getSurveyName());
        surveyName.setSpan(new StyleSpan(Typeface.NORMAL),0, surveyName.length(), Spannable
                .SPAN_EXCLUSIVE_EXCLUSIVE);
        mNextTv.setText(String.format(getContext().getString(R.string.cc_journal_survey_next), surveyName));

However my end result is

Next Survey: Survey

I thought that Typeface.NORMAL would take my spannable string and present it without bold.

What am I not understanding about this?

Upvotes: 2

Views: 4662

Answers (1)

muminers
muminers

Reputation: 1210

Your TextView has textStyle property set to bold. It overrides what you've set in your 'surveyName' variable. So my suggestion is to delete it and in your Spannable set span for the part of text that you want to be bold.

Try something like this:

final theWholeString = String.format(getContext().getString(R.string.cc_journal_survey_next), surveyName);
final SpannableString outputString = new SpannableString(theWholeString);
outputString.setSpan(new StyleSpan(Typeface.BOLD), 0, END_OF_BOLD_AREA, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

mNextTv.setText(outputString);

And remove testStyle from your TextView.

Upvotes: 4

Related Questions