android计数器——基础编
计数器是指一些常用计时器,例如体育比赛中测试时间的计时器等,但所要介绍的这种计时器一般原理,先让我们看一下图先让我们看一下代码的实现方法:packagecom.smart;importandroid.app.Activity;importandroid.content.Context;importandroid.os.Bundle;...
·
计数器是指一些常用计时器,例如体育比赛中测试时间的计时器等,但所要介绍的这种计时器一般原理,先让我们看一下图先
让我们看一下代码的实现方法:
- package com.smart;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.os.Handler;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class Main extends Activity implements OnClickListener, Runnable{
- private Handler handler;
- private TextView sCount;
- private int count=0;
- @Override//创建方法
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button sStart=(Button)findViewById(R.id.sStart);
- Button sStop=(Button)findViewById(R.id.sStop);
- Button showToast=(Button)findViewById(R.id.showToast);
- sCount=(TextView)findViewById(R.id.sCount);
- sStart.setOnClickListener(this);
- sStop.setOnClickListener(this);
- showToast.setOnClickListener(this);
- handler=new Handler();
- }
- //吐丝显示
- class RunToast implements Runnable{
- private Context context;
- public RunToast(Context context) {
- this.context = context;
- }
- @Override
- public void run() {//根据时间去显示内容
- Toast.makeText(context, "15秒后显示信息内容", Toast.LENGTH_LONG).show();
- }
- }
- @Override//事件点击
- public void onClick(View v) {
- switch (v.getId())
- {
- case R.id.sStart:
- handler.postDelayed(this, 5000);
- break;
- case R.id.sStop:
- handler.removeCallbacks(this);
- break;
- case R.id.showToast:
- handler.postAtTime(new RunToast(this)
- {
- }, android.os.SystemClock.uptimeMillis() + 15 * 1000);
- break;
- }
- }
- @Override//线程运行
- public void run() {
- sCount.setText("Count: "+String.valueOf(++count));//显示计数:
- handler.postDelayed(this, 5000);
- }
- }
main.xml文件写法
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/sCount"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Button
- android:id="@+id/sStart"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="开始计数"
- />
- <Button
- android:id="@+id/sStop"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="停止计数"
- />
- <Button
- android:id="@+id/showToast"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="15秒后显示Toast信息"
- />
- </LinearLayout>
转载于:https://blog.51cto.com/llb988/510350
更多推荐
已为社区贡献6条内容
所有评论(0)