Detect where Android's TextView would insert a line break

风格不统一 提交于 2019-12-05 08:12:35
Jim

TextView (Layout object) has some useful functions for what you are trying to accomplish:

http://developer.android.com/reference/android/text/Layout.html

take a look at:

getLineCount()

getLineEnd(int line)

You can get the substring for the TextView string based on where the character is located at each lineEnd.

You will need to use getViewTreeObserver() to wait until the TextView is drawn before you can call these and get useful information from them.

Alternatively, you can build a custom TextView that might provide the data through built-in methods or by adding a listener to it. An example of a custom TextView that modifies text size is here:

android ellipsize multiline textview

I've used that and did similar modifications (like what you are trying to do).

You'd probably want to wrap this logic into a custom view (overriding onSizeChanged()) but you can use the Layout class to check where each line ends:

textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // Remove immediately so it only fires once
        textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

        // View should be laid out, including text placement
        final Layout layout = textView.getLayout();
        float maxLineWidth = 0;

        // Loop over all the lines and do whatever you need with
        // the width of the line
        for (int i = 0; i < layout.getLineCount(); i++) {
            maxLineWidth = Math.max(maxLineWidth, layout.getLineWidth(i));
        }
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!