轉自:http://blog.csdn.net/lizzy115/article/details/7513552
float textWidth = textView.getPaint().measureText(text) + PaddingLeft + PaddingRight;
另外:
1)問題
在Android中實現自適應的TableCtrl控件顯示文字信息時,碰到有一個問題,就是需要得到一列中最長的字符串的寬度值。在網上搜索后,發現Android下可以利用 sdk 中已經提供的Paint的 measureText(String text) 方法。於是嘗試網上已經給出的代碼:
Paint paint = new Paint();float strWidth = paint.measureText(String);
控件中的各列按以上的調用並取得寬度的最大值,在設置后還是出現了字符串顯示時被截斷了,明顯是返回的寬度值仍然偏小。難道與混雜的字體有關?有沒有可能是這樣產生的Paint實例只是用到了默認的值?
(2)解決的過程
轉念想到了Paint是畫圖時的重要元素,留意到熟悉的TextView中正是有這樣的方法 getPaint() 返回的是TextPaint的實例(the base paint used for the text. Please use this only to consult the Paint's properties and not to change them.) Paint的運用是與特定的Context中的資源相關聯的,現在可以得到解決方案了。利用在TableCtrl中已經保存的Context(實際傳入的 是Activity的實例),作如下調用:
view sourceprint?TextView textView = new TextView(mContext);
Paint paint = textView .getPaint();
view sourceprint?float textWidth = paint.measureText(text);
經過測試,此時得到的textWidth值才是真正想要的。從而TableCtrl中單元格可以達到按最長的文字信息自動擴展顯示。
(3)進一步的討論
現在我們可以把注意力轉向TextView,在它的構造器里面有重要的一個參數Context,看到其父類View的構造器中對參數Context的 解釋:context, The Context the view is running in, through which it can access the current theme, resources, etc. 至此容易看出View的顯示是依賴於外部的Context的。
view sourceprint?public TextView (Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
...
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.density = getResource().getDisplayMetrics().density;
...
}
由以上TextView實現相關的部分源碼,可以發現TextPaint與Context可用的資源實際上是緊密相關的,也就容易知道之前對measureText方法的調用出現了什么問題。
常常看到在Activity派生類的onCreate()方法中,我們通常需要調用setContentView()設置與當前的Activity相 關聯的view進行顯示,下面也大體看一下這個過程的發生:Activity的setContentView()方法實際交由其內部的成員 ---Window類別的實例 mWindow來完成(注意到Window為抽象類,實際的mWindow是經過工廠方法產生的PhoneWindow的實例)。繼續挖出 PhoneWindow重寫setContentView()方法的相關源碼:
view sourceprint?@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mContentParent.addView(view, params);
final Callback cb = getCallback();
if (cb != null) {
cb.onContentChanged();
}
}
而mWindow是作為在Activity中的top-level view被加入進來的,另外可以看到在設置完view之后,PhoneWindow 獲取了初始注冊的外部回調方法,此時觸發調用實現對應的更新操作。