2

I can't figure out how to set superscript text (for mathematical operators) in an android button.

As the code below suggests, I want buttonXPow to display:

Xy

And I want button10Pow to display:

10y

I want to avoid having to resort to displaying X^y and 10^y where possible.


The only possible solution I've found so far is this code (found in this stackoverflow question here):

protected void onCreateView() {

    if (rootView.findViewId(R.id.buttonXPow) !=null) {
        ((Button) rootView.findViewById(R.id.buttonXPow)).setText(Html.fromHtml("X <sup><small> y </small></sup>"));
    }
    if (rootView.findViewId(R.id.button10Pow) !=null) {
        ((Button) rootView.findViewById(R.id.button10Pow)).setText(Html.fromHtml("10 <sup><small> y </small></sup>"));
    }
}

The problem with this is that rootView cannot be resolved. I'm not sure how I can get that working (obviously it's not a class I need to import; I'm assuming I need to declare a variable somehow).

Is there any other known way of setting superscript text; perhaps with xml rather than in the main java class?

Community
  • 1
  • 1
rst-2cv
  • 1,130
  • 1
  • 15
  • 31

2 Answers2

2

In your strings.xml file add the following-

<string name="test_string"> <![CDATA[ X<sup><small>2</small></sup> ]]> </string>

and then in your activity access it with-

getResources().getString(R.string.test_string)

this will work to get x^2

Anuraj Jain
  • 85
  • 10
  • The issue is not that the `setText(Html.fromHtml("X y "));` doesn't work, it's that `rootView` can't be resolved so the code doesn't even get that far. – rst-2cv Oct 15 '16 at 14:01
2

Adding the following to the onCreate method works

((TextView)findViewById(R.id.buttonXPow)).setText(Html.fromHtml("X<sup>y</sup>"));
((TextView)findViewById(R.id.button10Pow)).setText(Html.fromHtml("10<sup>y</sup>"));
rst-2cv
  • 1,130
  • 1
  • 15
  • 31