안드로이드 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);
}

참고 :  
http://docs.cena.co.kr/?mid=textyle&sort_index=regdate&order_type=desc&comment_srl=13049&listStyle=list&document_srl=42137 

+ Recent posts