我對android文檔的閱讀發現了方法forceLayout()(它將在下一個佈局請求時產生布局顯示)和requestLayout()(它應該發佈即時佈局請求),但我不能讓他們像廣告一樣行事。特別是,如果我在Thread.Sleep之前和之後設置了一個文本,它會一次性設置兩個文本之前等待Sleep完成,不管我是否在兩者之間調用forceLayout()和requestLayout()。請不要回應很多關於我不應該在UI線程中調用Thread.Sleep的廢話。如果我將Thread.Sleep包裝在CountDownTimer中,它可以很好地工作(只要我的tick時間足夠短,不會影響睡眠時間,並且計時器的持續時間足夠長以允許睡眠完成。一個例子:forceLayout(),requestLayout()
int i=0;
TextView tv2;
TextView tv1;
LinearLayout ll;
Button bt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
tv1=new TextView(this);
tv2=new TextView(this);
bt=new Button(this);
bt.setText("Press to start");
ll.addView(bt);
ll.addView(tv1);
ll.addView(tv2);
tv2.setText("");
setContentView(ll);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tv1.setText("starting sleep");
new CountDownTimer(6000,50){
public void onTick(long msuf)
{if(i==1)
{
try{
Thread.sleep(4000);
tv2.setText("waking up");
}
catch(InterruptedException e){};
}
i++;
}
public void onFinish(){}}.start();
}
});
}
另請參閱http://stackoverflow.com/questions/13856180/usage-of-forcelayout-requestlayout-and-invalidate – Suragch 2017-02-24 04:22:31