Solution 1 :
Instead of doing this, You can use bold tags in your string and display it in HTML form. See the code below
String text = itemView.getContext().getResources().getString( R.string.ActivityIShared_with, sharedTo.get( getAdapterPosition));
SpannableStringBuilder styledString;
if(SDK_INT > N) styledString = (SpannableStringBuilder) Html.fromHtml(,Html.FROM_HTML_MODE_COMPACT) else styledString = (SpannableStringBuilder) Html.fromHtml(result)
tv_Sharewith.setText(styledString.toString());
Solution 2 :
From what I can understand you are basically trying to concate string with some style. You can try this straight forward to solve your problem with little modification
Add this method
public static SpannedString buildString(String boldText, String regularText) {
final SpannableStringBuilder builder = new SpannableStringBuilder();
int start = builder.length();
builder.append(boldText);
builder.setSpan(new StyleSpan(BOLD), start, builder.length(), SPAN_INCLUSIVE_EXCLUSIVE);
builder.append(regularText);
return new SpannedString(builder);
}
and change
<string name="ActivityIShared_with">Shared with: %1$s</string>
to
<string name="ActivityIShared_with">Shared with:</string>
and use the method
buildString(context.getString(R.string.ActivityIShared_with), sharedTo.get(getAdapterPosition()));
This way you don’t have to keep count of text length referring ActivityIShared_with
Problem :
In one of my TextViews
I had like to set some of the text in a bold font like this:
In order do so I’m using the following:
final SpannableStringBuilder sb = new SpannableStringBuilder(itemView.getContext().getResources().getString( R.string.ActivityIShared_with, sharedTo.get( getAdapterPosition() ) ));
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
sb.setSpan(bss, 0, 11, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv_SharedWith.setText(sb);
Where
<string name="ActivityIShared_with">Shared with: %1$s</string>
As you can see this code works. However, I needed to count the length of the R.string.ActivityISharedwith
manually until the part of %1$s
which is 11 in order to make it bold.
Maybe in a few days, I will change that sentence and I would like to avoid counting its length every time.
How can I get the length of it but without the part of sharedTo.get( getAdapterPosition() )
? the string without the variable.
Thank you
Comments
Comment posted by Marco
did you try regex? ` String mydata = “String with: 1s$s”; Pattern pattern = Pattern.compile(“^[A-Za-z, ]+:”); Matcher matcher = pattern.matcher(mydata);` Something like that you neet to make pattern as static variable because that consume a lot each compilation