Multiple font size for button not working

2019-08-22 19:33发布

问题:

When I tried to set multiple font sizes for button text inside a recycler view it is not working as expected.

What I was trying to do is get the first letter of the text and make it a little bigger, add line break and then the actual text and set the whole text in the button.Here is the code I've tried, but is not working as expected (the size is not changing).

public void onBindViewHolder(final PopularCityViewHolder holder, int position) {
    if (shouldShowLoadingView()) return;
    PopularCity x = mItems.get(position);
    stringBuilder = new StringBuilder();
    stringBuilder.append(x.districtName.charAt(0));
    stringBuilder.append("\n\n");
    stringBuilder.append(x.districtName);

    SpannableString spannableString = new SpannableString(stringBuilder.toString());
    spannableString.setSpan(new RelativeSizeSpan(2.0f), 0,1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    holder.mBtn.getLayoutParams().width = prefWidthAndHeight;
    holder.mBtn.getLayoutParams().height = prefWidthAndHeight;
    String[] colors = colorCodes.get(position).split(",");
    int bg = Color.rgb(Integer.parseInt(colors[0]), Integer.parseInt(colors[1]), Integer.parseInt(colors[2]));
    holder.mBtn.setBackgroundColor(bg);
    holder.mBtn.setText(spannableString);
}

What is wrong in this code?

回答1:

try this my friend

TextView tv= (TextView) findViewById(R.id.tv2);
    String title="Nilesh";

    final SpannableString spannableString = new SpannableString(title);
    int position = 0;
    for (int i = 0, ei = title.length(); i < ei; i++) {
        char c = title.charAt(i);
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
            position = i;
            break;
        }
    }
    spannableString.setSpan(new RelativeSizeSpan(2.0f), position, position + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    tv.setText(spannableString, TextView.BufferType.SPANNABLE);