![](/img/trans.png)
[英]How would I check all the controls on a winform to make sure none of them have been edited before changing what's displayed?
[英]Check how many lines TextView will have before it's displayed
在我的應用程序中,我需要myTextView中的文本才能顯示單行,但末尾沒有三個點。 當文本太長時,我需要顯示格式略有不同的文本,因此設置maxHeight之類的內容將無濟於事,因為它只會裁剪文本。
我的方法是檢查TextView有多少行,如果文本多於1,則使文本變短。這正是我想要的方法,但是由於必須先繪制View才能檢查LineCount,即兩行布局在將文本剪切為單行之前短暫閃爍:
myTextView.Post(() =>
{
if (myTextView.LineCount > 1)
{
// make text shorter here to fit 1 line
}
});
所以我的問題是,有沒有什么辦法來檢查之前,它顯示給用戶的視圖將有多少行呢? 我可以根據字符串中的字符數來強制使用它,但這似乎是錯誤的。
首先,將“ TextView可見性”設置為“不可見”,以使其占用空間並填充。
您可以使用一種方法來獲取行數。
TextView txt = (TextView)findViewById(R.id.txt);
txt.getLineCount();
這將返回一個“ int”。 在textChangedListener中使用該int可以播放TextView的可見性。
這樣,您將知道TextView有多少個換行符。
干杯。
因此,我找到了一個適合我的解決方案。 它需要獲取屏幕寬度,計算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("-"));
}
現在來看,這是一種非常簡單的方法,但是我將其留在這里,也許有人會覺得它有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.