强制LeadingMarginSpan2的文本方向

时间:2015-07-26 13:21:58

标签: java android

我按照建议使用LeadingSpanMargin2来设置TextView的样式,使其围绕Image流动,问题是我设置的文本是动态的,可以是rtl或ltr

我尝试了任何我能想到的修复leadingMargin的内容,以便在两种情况下都是正确的或左边的,但无济于事。

此外,我已尝试在github中发布FlowTextView小部件,但在rtl情况下效果不佳,所以请不要建议。

非常感谢。

这是我使用的代码,在另一个答案中提出:

public void setFlowText(CharSequence text, int width , int height, TextView messageView)
{
    float textLineHeight = messageView.getPaint().getTextSize();

    // Set the span according to the number of lines and width of the image
    int lines = (int)Math.ceil(height / textLineHeight);
    //For an html text you can use this line: SpannableStringBuilder ss = (SpannableStringBuilder)Html.fromHtml(text);
    SpannableString ss = new SpannableString(text);
    ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    //ss.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    messageView.setText(ss);

    // Align the text with the image by removing the rule that the text is to the right of the image
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)messageView.getLayoutParams();
    int[]rules = params.getRules();
    rules[RelativeLayout.RIGHT_OF] = 0;
}

public class MyLeadingMarginSpan2 implements LeadingMarginSpan2 {
    private int margin;
    private int lines;
    private boolean wasDrawCalled = false;
    private int drawLineCount = 0;

    public MyLeadingMarginSpan2(int lines, int margin) {
        this.margin = margin;
        this.lines = lines;
    }

    @Override
    public int getLeadingMargin(boolean first) {
        boolean isFirstMargin = first;
        // a different algorithm for api 21+
        if (Build.VERSION.SDK_INT >= 21) {
            this.drawLineCount = this.wasDrawCalled ? this.drawLineCount + 1 : 0;
            this.wasDrawCalled = false;
            isFirstMargin = this.drawLineCount <= this.lines;
        }

        return isFirstMargin ? this.margin : 0;
    }

    @Override
    public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) {
        this.wasDrawCalled = true;
    }

    @Override
    public int getLeadingMarginLineCount() {
        return this.lines;
    }
}

1 个答案:

答案 0 :(得分:1)

由于某些未知原因,你可以通过传递左边距:

ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

并获得正确的保证金,您需要通过:

ss.setSpan(new MyLeadingMarginSpan2(lines, width), 1, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

我不知道那里发生了什么,但这很有效!