Android:单击按钮后的自定义时间后显示Toast消息

时间:2014-03-11 10:35:38

标签: android xml toast

我想在点击按钮30秒后添加吐司说法。你能帮帮我吗?

5 个答案:

答案 0 :(得分:5)

您可以Handler使用postDelayed()。您可以找到文档here

例如:

new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

             // Put your Toast here

        }
}, 30 * 1000);

您必须注意正在运行Handler的线程。如果您想进行UI修改(例如Toast),则必须在UI-Thread上附加Handler

答案 1 :(得分:2)

您可以使用postDelayed()的{​​{1}}方法...传递Handler和特定时间,之后Thread将执行如下...

Thread

然后在private Handler mTimerHandler = new Handler(); private Runnable mTimerExecutor = new Runnable() { @Override public void run() { Toast.makeText(Activity.this, "Button Clicked", Toast.LENGTH_LONG).show(). } }; 方法中调用如下...

onClick()

答案 2 :(得分:1)

new Handler().postDelayed(new Runnable() {

    @Override
    public void run() {
        // Toast message here
    }
}, 500);

答案 3 :(得分:1)

您可以在按钮点击事件上实现此功能。

button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

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

        @Override
        public void run() {
            // TODO Auto-generated method stub

            Toast.makeText(Activity.this, "Button Clicked", Toast.LENGTH_LONG).show();

    }, 3000);

        }
});

答案 4 :(得分:0)

单击按钮后可以启动计时器30秒,然后在onFinish()方法中显示吐司信息。

public class TestActivity extends Activity{

private MyCounter mCounter;
private Button mBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    mBtn=(Button)findViewById(R.id.btn);

    mBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mCounter=new MyCounter(40000, 10000);
            mCounter.start();
        }
    });
}

private class MyCounter extends CountDownTimer{

    public MyCounter(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), "Display your text here",                  Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub
        Log.i("on tick>>>>>>",millisUntilFinished+">>>>>");
    }
}
}