Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpannableString not working when using AppCompat theme

I'm unable to get SpannableString to work when I set AppTheme to Theme.AppCompat.Light.DarkActionBar.

I have a button and its text is set with a SpannableString. When I use Holo theme the text renders as expected, but when I switch to AppCompat theme the span effects seam to be ignored. How can I get the SpannableString to work using the AppCompat theme?

enter image description here

styles.xml - when switching between those 2 themes I get very different results...

<resources>
  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar" />
  <!--<style name="AppTheme" parent="@android:style/Theme.Holo.Light" />-->
</resources>

... for my button that uses SpannableString

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        Button button = (Button) rootView.findViewById(R.id.button);

        String detail = "ABC";
        String caption = String.format("2 %s", detail);
        Spannable span = new SpannableString(caption);

        int detailIndex = caption.indexOf(detail);

        span.setSpan(new StyleSpan(Typeface.BOLD), 0, detailIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new RelativeSizeSpan(0.5f), detailIndex, detailIndex+detail.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        button.setText(span);

        return rootView;
    }
}
like image 371
Aegir Avatar asked Jan 09 '23 15:01

Aegir


1 Answers

Well, it's not tied to appcompat-v7. If you remove the theme stuff entirely, and just use the default theme, on Android 5.0+ you will get Theme.Material, and the same effect can be seen there.

Part of the Material Design aesthetic is that button captions should be all caps, and however they implemented that is wiping out your spans. appcompat-v7 works with your code on pre-5.0 devices, suggesting that their backported widget effects do not include the app-caps stuff, and that they are delegating to the standard widgets on 5.0+.

Adding android:textAllCaps="false" to your Button in the layout seems to clear up the problem.

like image 199
CommonsWare Avatar answered Jan 17 '23 20:01

CommonsWare