【问题标题】:How to type x^2 (subscript and superscript) in TextView如何在 TextView 中输入 x^2(下标和上标)
【发布时间】:2017-12-13 17:08:34
【问题描述】:

我正在 Android Studio(Mac OS) 中制作一个计算器应用程序,我试图在其中包含 square(x^2) Button。 我已将我的方格设置为 TextView。

我已经尝试了所有提到的链接,但没有一个适合我以正确的公式格式输入。

<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" />

我也尝试过MainActivity.java 文件中的以下代码:-

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

尝试的示例 Source 1Source 2没用!

附:我设置了minSdkVersion 14targetSdkVersion 26

【问题讨论】:

  • if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { description_tv.setText(Html.fromHtml("x2",Html.FROM_HTML_MODE_COMPACT)); }
  • 试试这个库,它帮助我在 TextView 中显示数学函数 github.com/kexanie/MathView
  • setText 之后你在 TextView 中看到了什么
  • @Jacky 我在 TextView 中看到的只是 X2

标签: java android


【解决方案1】:

Android 原生支持子/上标类型文本,称为 SubscriptSpanSuperscriptSpan

上标的示例用法(例如 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);

我找到了一个非常好的example

【讨论】:

    【解决方案2】:

    只需做一些简短的研究,Html.fromHtml 在 Android N+ 中已被弃用。

    正确的方式应该是这样的:

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

    只需检查@Vishva Dave 的评论,对于 android 版本:

    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);
    

    【讨论】:

    • 谢谢,但它不起作用,仍然得到相同的 X2
    猜你喜欢
    • 2014-07-22
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2015-11-12
    • 2017-12-20
    • 2014-03-22
    相关资源
    最近更新 更多