2017-10-06 35 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就是它的下面。但感謝意見。 –

相關問題