package com.example.flowercatswets.test; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends ActionBarActivity { TextView tv; Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView) findViewById(R.id.text); mHandler=new Handler(); } @Override protected void onResume() { demoForLoop(); demoForLoop(); super.onResume(); } int i; private void demoForLoop() { for(i=0;i<1000000;i++) { mHandler.post(new Runnable() { @Override public void run() { tv.setText(String.valueOf(i)); } }); } } }
結果會變成下面這樣,迴圈叫你起床去尿尿後,就不管你了,然候
變成什麼都沒有顯示出來~直到Android把工作都消化完了。
換成用遞迴的方式呢
public class MainActivity extends ActionBarActivity { TextView tv; Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView) findViewById(R.id.text); mHandler=new Handler(); } @Override protected void onResume() { demorecursive(); super.onResume(); } int i; /*private void demoForLoop() { for(i=0;i<1000000;i++) { mHandler.post(new Runnable() { @Override public void run() { tv.setText(String.valueOf(i)); } }); } }*/ private void demorecursive() { i=0; Runnable mRunable=new Runnable() { @Override public void run() { tv.setText(String.valueOf(i++)); mHandler.postDelayed(this, 1); if (i==1000001) { mHandler.removeCallbacks(this); } } }; mHandler.postDelayed(mRunable, 1); } }
會看到數字狂飆,其實它們的差異在於,一個尿完叫下一個起來尿尿,這樣才不會大家都去搶廁所
沒有留言:
張貼留言