New Layout file activity_main.xml
<?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" tools:context=".MainActivity"> <Button android:id="@+id/btnOk" android:layout_width="wrap_content" android:layout_height = "start time" Android: text= "wrap_content" android:textSize="15dp" /> <TextView android:id="@+id/tvTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15dp" /> </LinearLayout>
New MainActivity.java
package com.example.administrator.timer; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btnOk; private TextView tvTime; private boolean bStart=false; private Handler mHander=new Handler(); private int mCount=0; private Runnable mCounter=new Runnable() { @Override public void run() { mCount++; tvTime.setText("当前计数值:"+mCount); mHander.postDelayed(this,1000); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { btnOk = (Button) findViewById(R.id.btnOk); tvTime = (TextView) findViewById(R.id.tvTime); btnOk.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnOk: if (bStart==false){ btnOk.setText("停止计时"); mHander.post(mCounter); }else{ btnOk.setText ( "start time" ); mHander.removeCallbacks (mCounter); } bStart ! = bStart; BREAK ; } } }
Hair often use Handler start the task. The following is a common method of treating Handler Runnable task description:
● post: Start Runnable task immediately.
● postDelayed: time to start after a delay of several Runnable task.
● postAtTime: Runnable task to start at a specified time.
● removeCallbacks: Remove the specified Runnable task.