我认为这与以字符为单位设置TextView的宽度相反。
我有一个TextView,其中显示了一些报告数据。我使用等宽字体类型的TypefaceSpan部分内容,因为我希望列能够对齐。
我使用我的测试Android设备来确定可以容纳多少列,但是Android模拟器似乎少了一列,这使得在纵向模式下换行方式不美观。
有没有办法找出应该放在一行上的字符数?
我认为这与以字符为单位设置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());
}
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));
}
你可以通过计算来找到答案,找出字符的宽度,将屏幕的宽度除以字符的宽度,就能得到你要找的结果。
但是难道没有更好的设计方法吗?有没有可以合并的列?可以显示为图形,甚至可以完全排除掉?
另一个可能的解决方案是使用类似于viewpager的东西。(找出第一页上适合多少列的宽度,然后将剩余的表格拆分到第二页)。
.append(substring)
应该使用大写字母 S:.append(subString)
。 - Cullub