2012-07-16 46 views
1

我覺得這是 Set width of TextView in terms of charactersGET寬度

相反我有一個TextView在那裏我展示了一些報告數據。我使用一個等寬的TypefaceSpan作爲它的一部分,因爲我想要列排成一行。

我用我的測試Android設備來弄清楚我可以安裝多少列,但Android模擬器似乎只有一個較少的列,這使縱向模式下以醜陋的方式進行換行。

有沒有辦法找出一行中應該放入多少個字符?

回答

10

答案是使用textView的Paint Object的breakText()。這裏是一個示例,

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

現在totalCharstoFit包含可以適合一行的確切字符。現在,你可以做一個子串完整的字符串,並將其追加到這樣TextView的,

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

那麼你可以做數學來找出這個問題,找到角色的寬度,用這個劃分屏幕的寬度,然後你就會找到你想要的東西。

但是難以設計它更好嗎?有沒有可以組合在一起的列?顯示爲圖形,甚至完全排除?

另一種可能的解決方案是使用類似viewpager的東西。 (找出第一頁上有多少列的寬度,然後將其餘表格分割到第二頁上)。

+0

http://filamentgroup.com/lab/responsive_design_approach_for_complex_multicolumn_data_tables/是另一種可能的解決方案。 – Stuart 2012-07-16 02:01:06

1

你可以得到的TextView的總線通過下面的代碼獲取每個字符的字符串。然後,您可以根據需要爲每行設置樣式。

我將第一行加粗。

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); 
      } 
     } 
    }); 
} 

試試這種方式。您可以使用這種方式應用多種樣式。

您還可以通過獲得的TextView的寬度:

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