以字符获取textview的宽度

时间:2012-07-16 01:49:28

标签: android layout

我认为这与之相反 Set width of TextView in terms of characters

我有一个TextView,我正在显示一些报告数据。我使用等宽字体TypefaceSpan作为其中的一部分,因为我希望列排成一行。

我使用我的测试Android设备来确定我可以容纳多少列,但Android模拟器似乎只有少了一列,这使得事物在纵向模式下以难看的方式包裹。

有没有办法找出一行中应该包含多少个字符?

3 个答案:

答案 0 :(得分:12)

答案是使用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());

}

答案 1 :(得分:1)

嗯,你可以做数学找出这个,找到角色的宽度,用此划分屏幕的宽度,你就拥有了你正在寻找的东西。

但是不可能更好地设计它吗?您可以将任何列组合在一起吗?显示为图形,甚至完全排除?

另一种可能的解决方案是使用类似viewpager的东西。 (找出第一页上有多少列宽度,然后将剩余的表格拆分到第二页)。

答案 2 :(得分: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));
}