-1

I am making a calculator app in Android Studio(Mac OS) in which I'm trying to include square(x^2) Button. I've set my square as a TextView.

I've tried all the links mentioned but none worked for me to type it as in proper equation format.

<TextView
    android:id="@+id/square"
    style="?android:attr/borderlessButtonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:layout_marginBottom="-3dp"
    android:layout_marginLeft="-20dp"
    android:layout_marginStart="-5dp"
    android:padding="15dp"
    android:textColor="@color/black"
    android:textSize="18sp" />

I've also tried below code in MainActivity.java file:-

squareButton = findViewById(R.id.square);
squareButton.setText(Html.fromHtml("x<sup>2</sup>"));

Examples tried Source 1 Source 2 Didn't work!

P.S. I've set minSdkVersion 14 and targetSdkVersion 26!

Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
Vrishank Gupta
  • 47
  • 1
  • 2
  • 10

2 Answers2

8

Android has native support for sub/superscript type text know as SubscriptSpan and SuperscriptSpan

Sample Usage of Superscript (eg X^2)

String text = "X2";
SuperscriptSpan superscriptSpan = new SuperscriptSpan();
SpannableStringBuilder builder = new SpannableStringBuilder(text);
builder.setSpan(
                superscriptSpan,
                text.indexOf("2"),
                text.indexOf("2") + String.valueOf("2").length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

yourTextView.setText(builder);

I have found a really good example.

Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
1

Just do some short research, Html.fromHtml is deprecated in Android N+.

Correct way should be this:

strButton = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);

Just do a check like @Vishva Dave 's comment, for android versions:

String strButton;
String html = "x<sup>2</sup>";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    strButton = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
}
else{
    strButton = Html.fromHtml(html);
}

squareButton.setText(strButton);
Jacky
  • 2,924
  • 3
  • 22
  • 34