1. 程式人生 > >延時跳轉頁面

延時跳轉頁面

延時跳轉頁面(Handler的方式)

/**

  • 延時跳轉頁面
    */
    public class MainActivity extends Activity {

    private TextView text_time;
    private int time = 5;// 記錄倒計時
    private Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
    if (msg.what == 0) {
    if (time > 0) {
    time–;
    text_time.setText(time + “s”);
    // 重新發送訊息
    handler.sendEmptyMessageDelayed(0, 1000);
    } else {
    // 跳轉
    Intent intent = new Intent(MainActivity.this,
    SecondActivity.class);
    startActivity(intent);
    finish();
    }
    }
    };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // 初始化控制元件
    text_time = (TextView) findViewById(R.id.text_time);
    // 進入頁面,執行倒計時—延遲1s傳送一條訊息
    handler.sendEmptyMessageDelayed(0, 1000);
    }

    public void tiao(View view) {
    // 跳轉
    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
    startActivity(intent);
    handler.removeCallbacksAndMessages(null);
    finish();
    }
    }