您的位置:首页 > 其它

简单开始,暂停,继续的倒计时实现

2016-06-20 23:39 483 查看
关于实现“倒计时”功能的代码(包括开始、暂停、继续功能):

1、首先在布局文件中添加一个TextView和Button控件,并在onCreate方法中获得到TextView和Button的id;

2、在activity中定义一个int类型计时的初始值,和boolean类型的判断值(用于修改button按钮的显示文本的修改)

3、在activity中添加button的点击事件OnClickListener,重写onclick方法

4、用if语句判断,修改button按钮的显示的文本(“暂停或继续”)

5、这里使用两种方法实现倒计时,具体代码如下:

private TextView
text01;

   private Button
btn01;

   private
int
index = 20;

   private
boolean
isflag;

 

   @Override

   protected
void
onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);

      text01 = (TextView) findViewById(R.id.text01);

      btn01 = (Button) findViewById(R.id.btn);

      // btn01.setText("开始");

      btn01.setOnClickListener(new OnClickListener() {

//方法一(工作线程给主线程发送消息):

         @Override

         public
void
onClick(View v) {

            if (!isflag) {

               btn01.setText("暂停");

               isflag = true;

               final Handler
h = new Handler()
{//关联的是主线程

               public
void
handleMessage(Message msg) {

                  text01.setText(String.valueOf(msg.what));

               };

            };

            new Thread() {//新建工作线程

               public
void
run() {

                  while (index >= 0 &&
isflag) {

                     h.sendEmptyMessage(index);//
工作线程给主线程发消息

                     index--;

                     try {sleep(1000);}

catch (InterruptedException
e) {}

                  }

               };

            }.start();//启动线程

            } else {

               isflag = false;

               btn01.setText("继续");

            }

         }

//方法二:

@Override

         public
void
onClick(View v) {

            if (!isflag) {

               btn01.setText("暂停");

               isflag = true;

               final Handler
h = new Handler();//
默认关联当前线程(主线程)

               h.postDelayed(new Runnable() {

               public
void
run() {

                  if (index >= 0 &&
isflag) {

                     text01.setText(String.valueOf(index));

                     index--;

                     h.postDelayed(this, 1000);

                  }

               }

            }, 1000);

         }

      });

   }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: