2012-07-16 3 views
1

나는 이것이 내가 몇 가지 보고서 데이터를 표시하고있어 텍스트 뷰를 Set width of TextView in terms of charactersGET 폭은

의 반대라고 생각합니다. 컬럼이 정렬되기를 원하기 때문에 부분 공간에 대해 모노 스페이스 인 TypefaceSpan을 사용합니다.

필자가 테스트 한 안드로이드 장치를 사용하여 필자가 맞출 수있는 열의 수를 계산했지만, 안드로이드 에뮬레이터는 세로 열 모드에서보기 싫은 방법으로 줄 바꿈하는 열이 하나 밖에없는 것으로 보입니다.

한 줄에 몇 개의 문자를 넣을 수 있는지 찾는 방법이 있습니까?

답변

10

답은 textView의 Paint 객체의 breakText()를 사용하는 것입니다. 다음은 샘플,

int totalCharstoFit= textView.getPaint().breakText(fullString, 0, fullString.length(), 
true, textView.getWidth(), null); 

지금 totalCharstoFit 한 줄에 적합 할 수있는 정확한 문자가 포함입니다. 그리고 지금 당신이 당신의 전체 문자열의 하위 문자열을 확인하고이 같은 텍스트 뷰에 추가,

String subString=fullString.substring(0,totalCharstoFit); 
textView.append(substring); 

그리고 나머지 문자열을 계산할 수 있습니다, 당신은 이제 전체를

fullString=fullString.substring(subString.length(),fullString.length()); 

을 수행 할 수 있습니다 코드가

는, while 루프에서이 작업을 수행

while(fullstirng.length>0) 
{ 
int totalCharstoFit= textView.getPaint().breakText(fullString, 0, fullString.length(), 
    true, textView.getWidth(), null); 
String subString=fullString.substring(0,totalCharstoFit); 
    textView.append(substring); 
fullString=fullString.substring(subString.length(),fullString.length()); 

} 
1

글쎄, 당신은 이것을 알아 내기 위해 수학을 할 수 있고, 글자의 너비를 찾고, 이것으로 화면 너비를 나눌 수 있습니다. 그러면 당신은 찾고있는 것을 가질 수 있습니다.

하지만 더 좋게 디자인 할 수 있습니까? 함께 그룹화 할 수있는 열이 있습니까? 그래픽으로 표시하거나 완전히 제외 할 수 있습니까?

또 다른 가능한 해결책은 뷰 페이지와 같은 것을 사용하는 것입니다. (첫 번째 페이지에 몇 개의 열 너비가 맞는지 확인한 다음 나머지 테이블을 두 번째 페이지로 나눕니다.)

+0

http://filamentgroup.com/lab/responsive_design_approach_for_complex_multicolumn_data_tables/는 다른 가능한 솔루션입니다. – Stuart

1

당신은 텍스트 뷰의 전체 라인을 얻을 수 있으며, 아래의 코드로 각 문자에 대한 문자열을 가져옵니다. 그러면 원하는 각 줄마다 스타일을 설정할 수 있습니다.

첫 줄을 굵게 설정했습니다.

private void setLayoutListner(final TextView textView) { 
    textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      textView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 

      final Layout layout = textView.getLayout(); 

      // Loop over all the lines and do whatever you need with 
      // the width of the line 
      for (int i = 0; i < layout.getLineCount(); i++) { 
       int end = layout.getLineEnd(0); 
       SpannableString content = new SpannableString(textView.getText().toString()); 
       content.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, end, 0); 
       content.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), end, content.length(), 0); 
       textView.setText(content); 
      } 
     } 
    }); 
} 

이렇게하면 다양한 스타일을 적용 할 수 있습니다.

당신은 또한에 의해 텍스트 뷰의 폭을 얻을 수 있습니다 :

for (int i = 0; i < layout.getLineCount(); i++) { 
     maxLineWidth = Math.max(maxLineWidth, layout.getLineWidth(i)); 
}