按钮文字SPANNABLE不适用

时间:2018-06-21 12:42:41

标签: android android-fragments

我正在使用SpannableStringBuilder将不同的样式应用于Button中的文本。但这并不适用。

    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(valueText);
    spannableStringBuilder.setSpan(new TextAppearanceSpan(mContext, R.style.ListItemButtonTitleTheme), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableStringBuilder.setSpan(new TextAppearanceSpan(mContext, R.style.ListItemButtonValueTheme), 6, valueText.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  holder.valueButton.setText(spannableStringBuilder.toString(), Button.BufferType.SPANNABLE);

list_item.xml

<Button
            android:id="@+id/value_button"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintWidth_percent="0.25"
            app:layout_constraintDimensionRatio="1:0.7"
            style="@style/ListItemButtonTheme"
            app:layout_constraintTop_toBottomOf="@id/hr_line_2"
            app:layout_constraintStart_toEndOf="@id/type_button"
            app:layout_constraintEnd_toStartOf="@id/sell_button"
            android:text="Google"
            />

styles.xml

<style name="ListItemButtonTitleTheme" parent="@android:style/Widget.TextView">
        <item name="android:textColor">@color/list_item_content_text_color</item>
        <item name="android:textSize">25sp</item>
        <item name="font">@font/proxima_nova_semibold</item>
        <item name="android:textAllCaps">false</item>
    </style>

    <style name="ListItemButtonValueTheme" parent="@android:style/Widget.TextView">
        <item name="android:textColor">@android:color/black</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">20sp</item>
        <item name="font">@font/proxima_nova_semibold</item>
        <item name="android:textAllCaps">false</item>
    </style>

1 个答案:

答案 0 :(得分:0)

使用AppCompactButton代替Button

<android.support.v7.widget.AppCompatButton
        android:id="@+id/value_button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintWidth_percent="0.25"
        app:layout_constraintDimensionRatio="1:0.7"
        style="@style/ListItemButtonTheme"
        app:layout_constraintTop_toBottomOf="@id/hr_line_2"
        app:layout_constraintStart_toEndOf="@id/type_button"
        app:layout_constraintEnd_toStartOf="@id/sell_button"
        android:text="Google"
        />

并将更改范围更改为Spanned

  SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(valueText);
  spannableStringBuilder.setSpan(new TextAppearanceSpan(mContext, R.style.ListItemButtonTitleTheme), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  spannableStringBuilder.setSpan(new TextAppearanceSpan(mContext, R.style.ListItemButtonValueTheme), 6, valueText.length()-1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  holder.valueButton.setText(spannableStringBuilder.toString(), Button.BufferType.SPANNABLE);