2017-10-06 34 views
0

在我的应用程序中,我需要在myTextView中显示单行,而不在末尾显示三个点。当它太长时,我需要显示一些不同格式的文本,所以像设置maxHeight这样的东西不会有帮助,因为它只是裁剪它。检查TextView在显示之前会有多少行

我的方法是检查TextView有多少行,并且如果文本大于1,则使文本更短。这正是我想要的方法,但由于必须首先绘制View以检查LineCount,两线布局闪烁剪切文本到一个行前简要:

myTextView.Post(() => 
    { 
     if (myTextView.LineCount > 1) 
     { 
      // make text shorter here to fit 1 line 
     } 
    }); 

所以我的问题是,有没有什么办法来检查多少行查看收到被显示给用户?我可以根据字符数计算字符串强制它,但这似乎是错误的。

+0

你可以添加一个侦听器到'textview'的'addTextChangedListener'和'afterTextChanged'中,计数'\ n'字符吗? –

+0

也许你可以用它来检查你的视图才出现https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html –

+0

GlobalLayout事件让我觉得我从来没有看到“长“文本了,但布局仍然闪烁着双线。 TextChanged事件没有\ n字符,并且LineCount当然是0。 –

回答

0

所以我来到了一个适合我的解决方案。它需要获取屏幕宽度,计算TextView的宽度并检查文本长度,以及dp中的所有内容。所以:

// get the screen width 
var metrics = Resources.DisplayMetrics; 
var widthInDp = (int)((metrics.WidthPixels)/metrics.Density); 

// this line is very specific, it calculates the real usable space 
// in my case, there was padding of 5dp nine times, so subtract it 
var space = widthInDp - 9 * 5; 

// and in this usable space, I had 7 identical TextViews, so a limit for one is: 
var limit = space/days.Length; 

// now calculating the text length in dp    
Paint paint = new Paint(); 
paint.TextSize = myTextView.TextSize; 
var textLength = (int)Math.Ceiling(paint.MeasureText(myTextView.Text, 0, myTextView.Text.Length)/metrics.Density); 

// and finally formating based of if the text fits (again, specific) 
if (textLength > limit) 
{ 
    myTextView.Text = myTextView.Text.Substring(0, myTextView.Text.IndexOf("-")); 
} 

现在看起来很简单,但我只是把它留在这里,也许有人会觉得它有用。

1

首先,将TextView Visibility设置为不可见,以便占据其空间并填充它。

有一种方法可以用来计算行数。

TextView txt = (TextView)findViewById(R.id.txt); 
txt.getLineCount(); 

这将返回 “INT”。 在textChangedListener中使用该int来使用TextView的可见性进行播放。

这样你就会知道TextView有多少换行符。

干杯。

+0

的方法不适合我。即使看不见,TextView也会混乱我的布局,因为另一个View就是它的下面。但感谢意见。 –

相关问题