[英]get width of textview in characters
我認為這與TextView的字寬設置相反
我有一個TextView,我正在顯示一些報告數據。 我使用等寬字體TypefaceSpan作為其中的一部分,因為我想要列排列。
我使用我的測試Android設備來計算出我可以容納多少列,但Android模擬器似乎只有少了一列,這使得事物在縱向模式下以難看的方式包裹。
有沒有辦法找出一行中應該有多少個字符?
答案是使用textView的Paint對象的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());
}
好吧,你可以做數學找出這個,找到角色的寬度,用這個划分屏幕的寬度,你就得到了你想要的東西。
但是不可能更好地設計它嗎? 您可以將任何列組合在一起嗎? 顯示為圖形,甚至完全排除?
另一種可能的解決方案是使用類似viewpager的東西。 (找出第一頁上有多少列的寬度,然后將剩余的表分成第二頁)。
您可以通過以下代碼獲取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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.