[英]How to wait after UI thread in Android?
在我的活動中,我有一個方法可以根據TextView的寬度來增大或減小字體大小。 我在TextView上執行setText以輸入新值(這很可能會增加或減小ViewText的寬度),然后直接進入我的方法。 我的問題是,當我輸入方法時,TextView的大小尚未更改,因此我猜測UI線程將花費更多時間來完成TextView的大小調整,因此我的方法無法正常工作。 那么,如何在UI線程之后等待,以便我可以正確執行方法的代碼?
這是我主要活動的代碼。 方法texteAffichage只是設置TextView中的內容,如果需要,gestionPolice會調整字體大小。 當我在gestionPolice中執行sysout時,我永遠都無法獲得TextView的當前寬度,因為似乎沒有時間這樣做。
affichage.setText(texteAffichage((Button) v));
gestionPolice();
我的建議是:
tv.setText("someText");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
int width = tv.getWidth();
// your code reacting to the change in width
}
}, 50);
50毫秒應該足以完成UI更改,但足以讓用戶忽略。
正如西蒙正確指出的那樣,這不一定是最佳解決方案。 舉例說明如何使用GlobalLayoutListener :
final ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
width = tv.getWidth();
// your code reacting to the change in width
}
});
您可以使用Handler 延遲代碼:
Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
// DO DELAYED STUFF
}
}, your_variable_amount_of_time); // e.g. 3000 milliseconds
旁注:我不認為發生您的問題是因為setText(...)方法花費了太多時間。 發布您的代碼,以便其他人可以看一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.