Android: How do i make nonbreakable block in TextV

2019-01-26 12:33发布

I have long text containing name that looks like "something-something". This long text is shown in TextView. The problem is "something-something" got line breaked.

I have found unicode character U+2011 NON-BREAKING HYPHEN. But it looks like this unicode character is supported in font since Android 3.0. However I'm supporting Android 2.1 where replacement character is shown instead.

I have looked at class Spannable, but I did not find how to define nonbreaking block of text. Maybe I overlook something.

1条回答
Fickle 薄情
2楼-- · 2019-01-26 13:25

I solved breaking of the text block by implementing ReplacementSpan to render text in single block. Here is the code:

public class NonbreakingSpan extends ReplacementSpan {

    @Override
    public void draw(
            Canvas canvas,
            CharSequence text, int start, int end,
            float x, int top, int y, int bottom,
            Paint paint) {
        canvas.drawText(text, start, end, x, y, paint);
    }

    @Override
    public int getSize(
            Paint paint,
            CharSequence text, int start, int end,
            FontMetricsInt fm) {
        return Math.round(paint.measureText(text, start, end));
    }
}
查看更多
登录 后发表回答