当前位置: 动力学知识库 > 问答 > 编程问答 >

Android : How to repeat a Toast every second

问题描述:

I am using a toast for Count Down Timer, so the toast should change it's text in every second. I use this to display the toast for exactly 1 second but i want the toast to repeat itself. Hope i make you understand.

 toast = Toast.makeText(getApplicationContext(), text.getText().toString(), Toast.LENGTH_SHORT); toast.show();

Handler handler = new Handler();

handler.postDelayed

(new Runnable() {

@Override

public void run() {

toast.cancel();

}

}, 1000);

网友答案:

This will show a new toast every second for exactly one second.

    int count = 100; //Declare as inatance variable

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    final Toast toast = Toast.makeText(
                            getApplicationContext(), --count + "",
                            Toast.LENGTH_SHORT);
                    toast.show();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            toast.cancel();
                        }
                    }, 1000);

                }
            });
        }
    }, 0, 1000);
网友答案:

run() is called after every second. so show toast there.

Handler handler = new Handler();
    handler.postDelayed 
               (new Runnable() {

              @Override
                 public void run() {
                            toast.cancel();
                            toast = Toast.makeText(getApplicationContext(), text.getText().toString(),Toast.LENGTH_SHORT);
                            toast.show();
            }
        }, 1000);
网友答案:

This page describes a way to keep the toast be shown indefinitely. So when you have the text view of the toast on hand, you may change the text as you like.

网友答案:
  1. you have to learn more about android srvices
  2. create java class extends from IntentService
  3. override this function

    @Override
    protected void onHandleIntent(Intent intent) {
    
        try {
            Toast.makeText(context,"Click on Location button to find your bus !",Toast.LENGTH_LONG).show();
    
            Thread.sleep(5000);
        } catch (InterruptedException e) {
    
            Thread.currentThread().interrupt();
        }
    }
    
  4. go to manifest an type

  5. go to your launcher java class and

    Intent intent = new Intent(this, Service_toast.class);
        startService(intent);
    
  6. ====>> for more information about services vist android devloper : https://developer.android.com/guide/components/services.html

分享给朋友:
您可能感兴趣的文章:
随机阅读: