[embedyt] https://www.youtube.com/watch?v=3pgGVBmSVq0[/embedyt]
activity_main.xmlMainActivity.java
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 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" android:orientation="vertical" tools:context="com.codinginflow.handlerpostdelayedexample.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startRepeating" android:text="start repeating" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="stopRepeating" android:text="stop repeating" /> </LinearLayout>
package com.codinginflow.handlerpostdelayedexample; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Handler mHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startRepeating(View v) { //mHandler.postDelayed(mToastRunnable, 5000); mToastRunnable.run(); } public void stopRepeating(View v) { mHandler.removeCallbacks(mToastRunnable); } private Runnable mToastRunnable = new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "This is a delayed toast", Toast.LENGTH_SHORT).show(); mHandler.postDelayed(this, 5000); } }; }