Cannot Wrap Blockquote-like Textview Of Arbitrary Line Count By Width
I need to render a quote block of arbitrary length. The text must be aligned to the left, while the block itself aligned to the right, similar to this one: For that I'm trying a T
Solution 1:
OK, after some examination of TextView
's code I put together the solution that does what I need:
package com.actinarium.persistence.common;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.text.Layout;
import android.util.AttributeSet;
import android.widget.TextView;
publicclassBlockquoteTextViewextendsTextView {
publicBlockquoteTextView(Context context) {
super(context);
}
publicBlockquoteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
publicBlockquoteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)publicBlockquoteTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@OverrideprotectedvoidonMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Now fix widthfloatmax=0;
Layoutlayout= getLayout();
for (inti=0, size = layout.getLineCount(); i < size; i++) {
finalfloatlineWidth= layout.getLineMax(i);
if (lineWidth > max) {
max = lineWidth;
}
}
finalintheight= getMeasuredHeight();
finalintwidth= (int) Math.ceil(max) + getCompoundPaddingLeft() + getCompoundPaddingRight();
setMeasuredDimension(width, height);
}
}
The default implementation of onMeasure
does not take line widths into account unless they are broken down by \n
's (code). I used getLineMax
instead of getLineWidth
because the latter measured trailing whitespace — the culprit of misalignment in block #3 in the original post.
Solution 2:
I am not sure of this but may work try adding dummy views with weight like this
<LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:weightSum="100"android:orientation="horizontal"><Viewandroid:layout_height="wrap_content"android:layout_weight="50"android:layout_width="0dp"/><TextViewandroid:layout_width="0dp"android:layout_weight="50"android:layout_height="wrap_content"android:layout_gravity="end"android:textAppearance="@style/TextAppearance.AppCompat.Body1"android:lineSpacingExtra="3.5dp"android:paddingLeft="24dp"android:layout_marginRight="24dp"android:text="Raw persistence may be the only option other than giving up entirely."
/></LinearLayout>
I have never tested this so give it a try...
Post a Comment for "Cannot Wrap Blockquote-like Textview Of Arbitrary Line Count By Width"