将前两个文本视图与不同的字体大小对齐

Align top two textviews with different font sizes

我正在使用约束布局,我想实现以下目标:

app:layout_constraintBaseline_toBaselineOf属性bottom对齐两个textview,请问有什么方法可以让两个textview顶部对齐?由于大小差异,常规 app:layout_constraintTop_toTopOf 当然不起作用。

试试这个 为此,您可以使用 Html.fromHtml

Html.fromHtml Returns displayable styled text from the provided HTML string.

yourTextview.setText(Html.fromHtml("<sup><small>$</small></sup>42"));

或者尝试使用 SpannableString

TextView textView = rootView.findViewById(R.id.tv);
SpannableStringBuilder sb = new SpannableStringBuilder("");
sb.setSpan(new SuperscriptSpan(), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(sb, TextView.BufferType.SPANNABLE);

这样做

String s = "$<sub>12 </sub>";
        textView.setText(Html.fromHtml(s)); // 12 will cropped 
// solution:
        s = "$<sub>12 </sub>\t  "; // add behind ending of sup tag the tabulator \t,
// but not char \t but only press to TAB key!!! in source code
        textView.setText(Html.fromHtml(s)); // 12 is visible correctly

http://android.okhelp.cz/whittled-superscript-sup-tag-textview-android-issue/

试试这个。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv_unit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="6dp"
        android:text="$"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:text="120"
        android:textSize="40sp"
        android:textStyle="bold"
        app:layout_constraintLeft_toRightOf="@+id/tv_unit"
        app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>

像这样。

因此似乎没有方便的方法来执行此操作,必须实现自定义视图。我从这里得到灵感:

https://github.com/fabiomsr/MoneyTextView