[英]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.