倒计时跳转

新建一个Activity,布局设置TextView,


xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".Countdown">

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50dp"
android:textColor="@color/purple_700"
android:id="@+id/count_text"/>

之后在Activity里面

public class Countdown extends AppCompatActivity {
private TextView mTextCount;
private int index=5;
private Runnable waitSendsRunnable;
private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_countdown);
    initView();
    initData();
    handler.post(waitSendsRunnable);
}

private void initData() {
     handler=new Handler(){
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 0:
                    Intent intent=new Intent(Countdown.this,MainActivity.class);
                    startActivity(intent);
                    break;

                case 1:
                    mTextCount.setText("倒计时: " + index + "s");
                    break;
                default:
                    break;
            }
        }
    };

    waitSendsRunnable = new Runnable() {
        @Override
        public void run() {

            if (index > 0) {
                index--;
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.post(waitSendsRunnable);
            }else {
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}

private void initView() {
    mTextCount = (TextView) findViewById(R.id.count_text);

}

}

你可能感兴趣的:(倒计时跳转)