Make a certain part of a android-textview align to the right
Asked Answered
R

7

20

I have this TextView. Some parts of it is supposed to be aligned to the left and some parts to the right. How would I do this in Java?

Basicly I want the first line to align to the left, and the next line to the right and so on.

Anyone got a clue?

EDIT

I have tried to use HTML and then when that did not work I tried spans.

html attempt

textView.setText(Html.fromHtml("<p align=\"right\">THIS IS TO THE RIGHT</p>"));

And heres the span attempt

    String LeftText = "LEFT";
    String RightText = "RIGHT";

    final String resultText = LeftText + "  " + RightText;
    final SpannableString styledResultText = new SpannableString(resultText);
    styledResultText.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), LeftText.length() + 1, LeftText.length() + 2 +RightText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(styledResultText);

But none of them seems to work.

Rockwell answered 25/1, 2013 at 11:24 Comment(0)
I
28
TextView resultTextView = new TextView(this);
final String resultText = LeftText + "  " + RightText;
final SpannableString styledResultText = new SpannableString(resultText);
styledResultText.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE)
    , LeftText.length() + 2
    , LeftText.length() + 2 + RightText.length()
    , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
resultTextView.setText(styledResultText);

Alignment.ALIGN_OPPOSITE is the equivalent for right side.

Alignment.ALIGN_NORMAL is the equivalent for left side.

Interlinear answered 25/1, 2013 at 11:35 Comment(7)
Hmm. It does´nt align to the right. Does the gravity in the textview matter?Rockwell
@Rockwell gravity of TextView do matters here. Try not to give android:gravity inside TextView in your xml.Interlinear
Hmm. I did´nt have gravity set to anyhthing in the xml before.. <TextView android:id="@+id/tvResult" android:layout_width="fill_parent" android:layout_height="fill_parent" android:maxLines="3" android:scrollbars="vertical" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#000" />Rockwell
This only works for me if i use the whole line with the span, but not for a part. :(Bergius
@Bergius AlignmentSpan.Standard is a paragraph style so you need to add a new line character to LeftText (i.e. \n ) to make RightTextright aligned. (I've not tested the particular example above)Colorable
For me, I could only get it to work with a linefeed "\n " instead of two spaces, and setting the second parameter of setSpan to LeftText.length() without the "+2". I've tried many combinations trying to get rid of the line feed that I don't want, but haven't come up with a satisfactory solution.Economize
Why it is presented as an answer while it does not work and can't work? its a paragraph-based span so it will work if we;ll make it TWO strings (with \n) but it could be trivially solved without spans then And with a single string it is useless :(Aetna
E
8

Here is a solution that works with Spannable, with the cavate that if the right and left are too wide, they will overlap on the same line. Since to do the Left/Right trick with a spannable requires a line feed between Left and Right, my fix is to add a spannable that reduces the line height to zero (i.e. overlapped lines) for the one linefeed and then restore normal line height after that.

    String fullText = leftText + "\n " + rightText;     // only works if  linefeed between them! "\n ";

    int fullTextLength = fullText.length();
    int leftEnd = leftText.length();
    int rightTextLength = rightText.length();

    final SpannableString s = new SpannableString(fullText);
    AlignmentSpan alignmentSpan = new AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE);
    s.setSpan(alignmentSpan, leftEnd, fullTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    s.setSpan(new SetLineOverlap(true), 1, fullTextLength-2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    s.setSpan(new SetLineOverlap(false), fullTextLength-1, fullTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

And we have the small routine to handle the overlapping lines:

    private static class SetLineOverlap implements LineHeightSpan {
    private int originalBottom = 15;        // init value ignored
    private int originalDescent = 13;       // init value ignored
    private Boolean overlap;                // saved state
    private Boolean overlapSaved = false;   // ensure saved values only happen once

    SetLineOverlap(Boolean overlap) {
        this.overlap = overlap;
    }

    @Override
    public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
                             Paint.FontMetricsInt fm) {
        if (overlap) {
            if (!overlapSaved) {
                originalBottom = fm.bottom;
                originalDescent = fm.descent;
                overlapSaved = true;
            }
            fm.bottom += fm.top;
            fm.descent += fm.top;
        } else {
            // restore saved values
            fm.bottom = originalBottom;
            fm.descent = originalDescent;
            overlapSaved = false;
        }
    }
}
Economize answered 7/4, 2016 at 22:42 Comment(1)
Nice trick, but doesn't work if the leftText is longer than 1 line in textview (without linefeed)Eponym
C
5

Thanks for the tip, @Frank, but this was just enough:

public class LineOverlapSpan implements LineHeightSpan {
    @Override
    public void chooseHeight(final CharSequence text, final int start, final int end, final int spanstartv, final int v, final Paint.FontMetricsInt fm) {
        fm.bottom += fm.top;
        fm.descent += fm.top;
    }
}

Used like this:

CharSequence text = return new Truss()
        .append("LEFT")
        .pushSpan(LineOverlapSpan())
        .append("\n")
        .popSpan()
        .pushSpan(AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE))
        .append("RIGHT")
        .build()

where Truss is

A SpannableStringBuilder wrapper whose API doesn't make me want to stab my eyes out.

Corona answered 11/9, 2016 at 3:12 Comment(0)
R
2

Two solution :

1) have a different text view for each line and set its gravity.

2) Use Html while loading data setting the alignment in html for it REF:how-to-display-html-in-textview This will not work align is not a supported tags Edited:

Also

3: will be to use a span.

Remote answered 25/1, 2013 at 11:28 Comment(4)
Hmm I tought that the second solution with HTML would be a great way to do it but it did´nt work.. textView.setText(Html.fromHtml("<H1 align=\"right\"> This should be to the right </H1>"));Rockwell
textView.setText(Html.fromHtml("<H1 align=\"right\"> This should be to the right </H1>")); Are you sure that the alignment from html works on the textview too?Rockwell
I just tried some samples and researched that HTML will not support alignment https://mcmap.net/q/662514/-alignment-in-html-fromhtmlRemote
Yep I just read that too.. But why is´nt the span solution working.. That should work, should´nt it?Rockwell
G
0

Simple.Adjust xml part in textview. Use layouts.If you want the textview to be in left

android:alignParentLeft="true" For more align details look this.

http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html

And this is also an example for different layouts.

http://www.androidhive.info/2011/07/android-layouts-linear-layout-relative-layout-and-table-layout/

Gunboat answered 25/1, 2013 at 11:34 Comment(0)
C
0

Inspired other solutions, but resolving multiline text issues and text overlap issue.

class LineOverlapSpan() : LineHeightSpan {
    var originalBottom: Int = 0
    var originalDescent: Int = 0
    var overlapSaved = false

    override fun chooseHeight(
        text: CharSequence?,
        start: Int,
        end: Int,
        spanstartv: Int,
        v: Int,
        fm: Paint.FontMetricsInt?
    ) {
        if (fm == null) {
            return
        }

        if (!overlapSaved) {
            originalBottom = fm.bottom
            originalDescent = fm.descent
            overlapSaved = true
        }

        if (text?.subSequence(start, end)?.endsWith("\n") == true) {
            fm.bottom += fm.top
            fm.descent += fm.top
        } else {
            fm.bottom = originalBottom
            fm.descent = originalDescent
        }
    }

}

Usage:

fun keyValueSpan(key: CharSequence, value: CharSequence) = span {
    span {
        alignment = "normal"
        +key
        span {
            textColor = Color.TRANSPARENT
            +value
        }
        span {
            +"\n"
            addSpan(LineOverlapSpan())
        }
    }
    span {
        alignment = "opposite"
        +value
    }
}

Kotlin solution is using Kpan library https://github.com/2dxgujun/Kpan

Cockatoo answered 15/7, 2019 at 6:41 Comment(1)
But it does not solve when you are using a BIG (lets say 24dp) text on left and then add in the same line a 10dp text aligned to the right... It cuts the big text on the bottom ? Any idea how to solve thatTerritoriality
I
0

I didn't want to create a custom view and I wasn't able to use the span answers here because I wanted to achieve this in a dialog with list items.

So, I just calculated how many spaces I would need to add to the middle of my string to get my text to fill the entire parent width and align part of it to the left.

Formula: ((width of parent - width of text) / width of single space) = number of spaces

For calculating text width, I used the answers from How to get string width on Android?

private fun calculateTextWidthPixels(context: Context, text: String, textSizeSp: Float): Int {
    val bounds = Rect()
    val textPaint = TextPaint().apply {
        typeface = Typeface.create("sans-serif", Typeface.NORMAL)
        textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, textSizeSp, context.resources.displayMetrics)
        getTextBounds(text, 0, text.length, bounds)
    }
    return StaticLayout.getDesiredWidth(text, textPaint).toAccurateInt()
}

private fun padMiddleOfTextWithSpaces(leftText: String, rightText: String, desiredWidthPixels: Int, textSizeSp: Float): String {
    val originalText = "$leftText $rightText"
    val originalTextWidth = calculateTextWidthPixels(context, originalText, textSizeSp)
    val singleSpaceTextWidth = calculateTextWidthPixels(context, " ", textSizeSp)
    val availableWidthForSpaces = desiredWidthPixels - originalTextWidth
    val spacesRequired = " ".repeat((availableWidthForSpaces / singleSpaceTextWidth))
    return "$leftText $spacesRequired$rightText"
}
Ideologist answered 13/9, 2022 at 5:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.