所以我來到了一個適合我的解決方案。它需要獲取屏幕寬度,計算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("-"));
}
現在看起來很簡單,但我只是把它留在這裏,也許有人會覺得它有用。
你可以添加一個偵聽器到'textview'的'addTextChangedListener'和'afterTextChanged'中,計數'\ n'字符嗎? –
也許你可以用它來檢查你的視圖纔出現https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html –
GlobalLayout事件讓我覺得我從來沒有看到「長「文本了,但佈局仍然閃爍着雙線。 TextChanged事件沒有\ n字符,並且LineCount當然是0。 –