Android TextView superscript

主宰稳场 提交于 2019-11-30 20:32:31

问题


So I'm trying to add superscipt/subscript to a TextView, basically trying to make a fraction be displayed as 1/2. Not sure where I'm going wrong, and I'm new with Android, so any help is appreciated. Thanks!

SpannableStringBuilder numSpan = new SpannableStringBuilder(String.valueOf(num));
SpannableStringBuilder denSpan = new SpannableStringBuilder(String.valueOf(den));

numSpan.setSpan(new SuperscriptSpan(), 0, numSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
denSpan.setSpan(new SubscriptSpan(), 0, denSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

outputText.setText(numSpan + "/" + denSpan, TextView.BufferType.SPANNABLE););

回答1:


Try Html.fromHtml instead. Simple and precise:

outputText.setText(Html.fromHtml("<sup>" + num + "</sup>/<sub>" + den + "</sub>"));

Note: You may need to give some height to the textview else the output will be clipped.

Alternatively, you could try this, where the number size is smaller:

outputText.setText(Html.fromHtml("<sup><small>" + num + "</small></sup>/<sub><small>" + den + "</small></sub>"));



回答2:


You can use RelativeSizeSpan

numSpan.setSpan(new SuperscriptSpan(), 0, numSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
numSpan.setSpan(new RelativeSizeSpan(0.5f), 0, numSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

or AbsoluteSizeSpan

numSpan.setSpan(new SuperscriptSpan(), 0, numSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
numSpan.setSpan(new AbsoluteSizeSpan(28), 0, numSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


来源:https://stackoverflow.com/questions/20597223/android-textview-superscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!