Align top two textviews with different font sizes

2019-07-14 16:44发布

Im using constraint layout and i want to achieve the following:

enter image description here

The app:layout_constraintBaseline_toBaselineOf attribute bottom aligns the two textviews, is there any way to top align the two? The regular app:layout_constraintTop_toTopOf is not working of course because of the size differences.

4条回答
霸刀☆藐视天下
2楼-- · 2019-07-14 16:57

Do this way

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/

查看更多
倾城 Initia
3楼-- · 2019-07-14 16:57

So it seems there is no a convenient way of doing this and a custom view must be implemented. I've taken inspiration from here:

https://github.com/fabiomsr/MoneyTextView

查看更多
成全新的幸福
4楼-- · 2019-07-14 17:18

try this you can use Html.fromHtml for this purpose

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

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

or try this use SpannableString

TextView textView = rootView.findViewById(R.id.tv);
SpannableStringBuilder sb = new SpannableStringBuilder("$42");
sb.setSpan(new SuperscriptSpan(), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(sb, TextView.BufferType.SPANNABLE);
查看更多
手持菜刀,她持情操
5楼-- · 2019-07-14 17:24

Try this .

<?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>

Like this .

enter image description here

查看更多
登录 后发表回答