androidDeveloer
androidDeveloer

Reputation: 95

How to display fractions in android textview?

I want to display on android text view. I tried doing it with unicode but no luck. Please see my code below. Can anyone please help.

additionalInfoString = additionalInfoString.replace("½",<sup><small>&frac12;</small></sup>);

Upvotes: 7

Views: 5141

Answers (5)

SilentKiller
SilentKiller

Reputation: 6942

You need to use HTML format to show fractions

tv.setText(Html.fromHtml("3<sup>1</sup>/<sub>2</sub>"));

Verify your HTML Text here.

enter image description here

As Html.fromHtml(String s) method has been depreciated. Take a look at this answer SO Answer

Upvotes: 7

maddy d
maddy d

Reputation: 1536

I would suggest you to create two TextView in a RelativeLayout and manage it. because in Html.fromHtml superscript text not comes with proper alignment . use some thing like below

 <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/maintext_sup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:gravity="top"
        android:text="1/2"
        android:textSize="10sp"/>

    <TextView
        android:id="@+id/maintext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:text="3"
        android:textSize="20sp" />
   </RelativeLayout>   

Upvotes: -1

MohK
MohK

Reputation: 1933

you can use unicode character directly as

tv.setText("3\u00BD");

this worked for me.

Upvotes: 1

jyomin
jyomin

Reputation: 1967

Try this:

mTxtVw.setText(Html.fromHtml("3<sup>1</sup>/<sub>2</sub>"));

Upvotes: 0

Antrromet
Antrromet

Reputation: 15414

You can use the html formatting of Android TextView. However you must add a extra space on the top and bottom to keep the fraction from being cut off.

  SpannableStringBuilder text = new SpannableStringBuilder();
  text.append("3");
  text.append("\n");
  text.append(Html.fromHtml("<sup>1</sup>/<sub>2</sub>"));
  text.append("\n");

P.S. : The above code is not tested (just a hunch)

Upvotes: 1

Related Questions