无法使用Html.fromHtml()为Android Button文本创建上标

时间:2015-03-22 20:16:34

标签: android android-layout formatting

我已经阅读了these questions这两个似乎有同样问题我正在努力解决的问题,即我的按钮文字我希望显示为标。在onCreateView方法的我的片段类中,我添加了

if (rootView.findViewById(R.id.squared) != null) {
                ((TextView) rootView.findViewById(R.id.squared)).setText(Html.fromHtml("X <sup><small> 2 </small></sup>"));
                rootView.findViewById(R.id.squared).setOnClickListener(this);
            }
if (rootView.findViewById(R.id.cubed) != null) {
                    ((TextView) rootView.findViewById(R.id.cubed)).setText(Html.fromHtml("X <sup><small> 3 </small></sup>"));
                    rootView.findViewById(R.id.cubed).setOnClickListener(this);

在我的fragment_main按钮被编码为

<Button
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:fontFamily="helvetica"
            android:id="@+id/squared"
            android:layout_weight="0.25"
            style="?android:attr/borderlessButtonStyle"
            android:textSize="15sp" />

 <Button
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:fontFamily="helvetica"
            android:id="@+id/cubed"
            android:layout_weight="0.25"
            style="?android:attr/borderlessButtonStyle"
            android:textSize="15sp" />

但是,当我运行我的应用程序时,布局不会有任何上标文本。

enter image description here

即使我将文字大小从15sp更改为10sp,文字也会变小,但不会上标。我做得不好?

2 个答案:

答案 0 :(得分:16)

如果可以,我会发表评论,但此时我无法做出评论。我刚刚发布了类似的东西,这个问题我也有。我中途解决了我的问题。 Html.fromHtml方法仅适用于textview,但不适用于我的butons。我只是想说这个,以防它或其他任何人想出如何在按钮上使用这种方法。我自己非常喜欢这个答案。

基本上: textview.setText(Html.fromHtml("x<sup>2</sup"));正确显示

但是button.setText(Html.fromHtml("x<sup>2</sup"));显示x2(没有上标)。

编辑:AlanV帮助了我。这是他向其他人提供的解决方案的链接。 https://stackoverflow.com/a/29056795/4535064

您需要做的就是将其添加到按钮中:

<button
    android:textAllCaps="false";/>

新版本5.0(我认为)强制按钮生成所有大写字母。当我在textview和按钮中生成相同的字符串时,我注意到这一点,并且按钮全部为大写,而textview则不是。因此,您不会看到HTML格式,例如和。将textAllCaps功能设置为&#34; false&#34;允许使用HTML。

再一次,给予应有的信誉,AlanV就是男人! : - )

答案 1 :(得分:0)

这是一个已知问题,如here所示。

我认为最好的办法是设置 android:textAllCaps =&#34; false&#34; ,然后将文本设置为自己大写。