在Android中使用替换时的换行符

时间:2014-12-23 11:05:05

标签: replace line-breaks

我使用replacementSpan为每个单词短语创建背景。 它适用于短语,但长短语错误

像这样:

a aa aaa aaa aaaa
123123

213123123123123123123123123

这是我的sourceCode

    public class FrameSpan extends ReplacementSpan {

    private final Paint mPaint;
    private int mWidth;

    public FrameSpan(int color) {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setColor(color);
        mPaint.setAntiAlias(true);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        mWidth = Math.round(paint.measureText(text, start, end));
        return mWidth;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        int line_space = bottom - top;
        canvas.drawRect(x, top, x + mWidth, bottom - line_space / 3, mPaint);
        canvas.drawText(text, start, end, x, y, paint);
    }

}


    List<String> tagList  = /* the list of phrases */
        int[] tagEndingIndex = /* the array contains the ending index of each phrases*/
        StringBuilder stringBuilder = /* the complete text created from tagList */
        SpannableString spannableString = new SpannableString(stringBuilder.toString());

        for (int i = 0; i < tagEndingIndex.length; i++) {
            int tagEndPos = tagEndingIndex[i];
            String currentTag = tagList.get(i);
            spannableString.setSpan(new FrameSpan(color), tagEndPos - currentTag.length() - 4, tagEndPos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        TextView.setText(spannableString, BufferType.SPANNABLE);

用长短语,我想要椭圆化它们。 请帮我。非常感谢你

1 个答案:

答案 0 :(得分:0)

您是否尝试过 android:ellipsize 属性?我认为许多与文本相关的视图组件都具有此属性。