android计数器――基础编
16lz
2022-05-19
计数器是指一些常用计时器,例如体育比赛中测试时间的计时器等,但所要介绍的这种计时器一般原理,先让我们看一下图先
让我们看一下代码的实现方法:
- packagecom.smart;
- importandroid.app.Activity;
- importandroid.content.Context;
- importandroid.os.Bundle;
- importandroid.os.Handler;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- importandroid.widget.TextView;
- importandroid.widget.Toast;
- publicclassMainextendsActivityimplementsOnClickListener,Runnable{
- privateHandlerhandler;
- privateTextViewsCount;
- privateintcount=0;
- @Override//创建方法
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- ButtonsStart=(Button)findViewById(R.id.sStart);
- ButtonsStop=(Button)findViewById(R.id.sStop);
- ButtonshowToast=(Button)findViewById(R.id.showToast);
- sCount=(TextView)findViewById(R.id.sCount);
- sStart.setOnClickListener(this);
- sStop.setOnClickListener(this);
- showToast.setOnClickListener(this);
- handler=newHandler();
- }
- //吐丝显示
- classRunToastimplementsRunnable{
- privateContextcontext;
- publicRunToast(Contextcontext){
- this.context=context;
- }
- @Override
- publicvoidrun(){//根据时间去显示内容
- Toast.makeText(context,"15秒后显示信息内容",Toast.LENGTH_LONG).show();
- }
- }
- @Override//事件点击
- publicvoidonClick(Viewv){
- switch(v.getId())
- {
- caseR.id.sStart:
- handler.postDelayed(this,5000);
- break;
- caseR.id.sStop:
- handler.removeCallbacks(this);
- break;
- caseR.id.showToast:
- handler.postAtTime(newRunToast(this)
- {
- },android.os.SystemClock.uptimeMillis()+15*1000);
- break;
- }
- }
- @Override//线程运行
- publicvoidrun(){
- sCount.setText("Count:"+String.valueOf(++count));//显示计数:
- handler.postDelayed(this,5000);
- }
- }
main.xml文件写法
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns: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>
更多相关文章
- Android系列教程之六:TextView小组件的使用--附带超链接和跑马灯
- Android的onCreateOptionsMenu()创建菜单Menu详解
- android 界面布局 很好的一篇总结
- android应用程序跳转到系统的各个设置页面
- Android控件Editext、TextView属性详解
- Android开发:还是Menu
- android强制横屏息屏后重新打开时会先显示竖屏
- Android下如何计算要显示的字符串所占的宽度和高度
- Android(安卓)adb devices显示no permission