관리 메뉴

드럼치는 프로그래머

[안드로이드] TextView 문자단위로 개행하기 본문

★─Programing/☆─Android

[안드로이드] TextView 문자단위로 개행하기

드럼치는한동이 2013. 11. 19. 11:04

안드로이드 TextView 기본 개행 단위는 아래 사진과 같이 스페이스(빈 공간)입니다.

 

이를 문자 단위의 개행으로, 아래와 같이 바꾸겠습니다.

 

 

아래 메쏘드는 제가 필요에 의해 만든 놈입니다.

(tistory에서 DynamicCoder님께서 작성하신 글을 참고하였습니다.)

 

/**

 * TextView의 문자열을 읽어와서 한 line에 width 만큼의 문자로 구성한다.

 * 이 때 width는 TextView의 width이다.

 *

 * @param textView 문자기준 개행을 적용하려는 대상 TextView.

 */

private void applyNewLineCharacter(TextView textView)
{
    Paint paint = textView.getPaint();
    String text = (String) textView.getText();
    int frameWidth = 118;
    int startIndex = 0;
    int endIndex = paint.breakText(text , true, frameWidth, null);  
    String save = text.substring(startIndex, endIndex);

    // Count line of TextView

    int lines = 1;


    while(true)
    {
        // Set new start index
        startIndex = endIndex;
        // Get substring the remaining of text
        text = text.substring(startIndex);


        if(text.length() == 0) break;

        else line++;

 

        if(lines == 4) // 3줄이 넘으면 줄임표(...)를 붙인다.
        {
            save = save.substring(0, save.length() - 2) + "...";
            break;
        }


        // Calculate end of index that fits
        endIndex = paint.breakText(text, true, frameWidth, null);
        // Append substring that fits into the frame
        save += "\n" + text.substring(0, endIndex);
    }
    // Set text to TextView
    textView.setText(save);
}

 

[출처] Android TextView 문자단위로 개행하기|작성자 jolangma

Comments