-1

I´m writing a calculator for chemistry in Android Studio and I have no idea about how to write the index of the elements in the given form:

H2O

With the index in the bottom left.

How can I achieve this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

4 Answers4

0

You will have to use SubscriptSpan. From official android documentation :

https://developer.android.com/reference/android/text/style/SubscriptSpan

Artory
  • 845
  • 7
  • 13
0

You might also want to take a look on this answer Subscript and Superscript a String in Android

Basically, since you need both subscript and superscript, a way to do this is through HTML, and you can add HTML on android.

TextView allows you to insert HTML.

Rainb
  • 1,965
  • 11
  • 32
0

The simplest way is to use html- Do like this:-

((TextView)findViewById(R.id.text)).setText(Html.fromHtml("H<sub>2</sub>O"));
Raj
  • 2,997
  • 2
  • 12
  • 30
0
private static CharSequence makeStringLikeFormula(String str) {
    if (str == null) return "";
    final SpannableString spannable = new SpannableString(str);
    final Matcher matcher = Pattern.compile("\\d+").matcher(str);
    while (matcher.find()) {
        spannable.setSpan(new SubscriptSpan(), matcher.start(), matcher.end(), 0);
    }
    return spannable;
}

example

textView.setText(makeStringLikeFormula("H2O22"));