Android APP:秒表

       这几天一直在看安卓,也正好赶上老师布置的作业,所以就做了一个秒表。自己参考了一下别人的图标,有了一些灵感所以顺便也设计了一下界面。下面先贴一下秒表的界面:

       打开秒表后的第一个界面:                                                  点击开始计时,开始键变为暂停,记录和停止开始变实:

                         

       点击记录:                                                                                              记录满了之后自动上移,通过滑动可以查看前面的:       

                         

       点击暂停:                                                                                              停止:

                                 

        重新开始和记录:                                                                                   双击返回键退出:

                                 

       下面贴出Activity的代码:

package com.example.stopwatch;

import java.util.Timer;
import java.util.TimerTask;

import android.R.bool;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
	
	
	private boolean mStart = false;
	private long mStartTime;
	private boolean mIsRecorded;
	private LinearLayout linearLayout;
	private int recordTimes;
	private long currentTime;
	private long lastTime = 0;
	private long tmpTime;
	private boolean isExit = false;
	
	//更新显示时间的关键
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (mStart) {
					updateTime();
					mHandler.sendEmptyMessage(1);
				}
				break;
			case 0:
				break;
			default:
				break;
			}
		}
	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		TextView textView1 = (TextView) findViewById(R.id.textView1);
		TextView textView2 = (TextView) findViewById(R.id.textView2);
		
		//修改时间的字体
		AssetManager mgr=getAssets();//得到AssetManager
		Typeface tf=Typeface.createFromAsset(mgr, "fonts/lanting.TTF");//根据路径得到Typeface
		textView1.setTypeface(tf);
		textView2.setTypeface(tf);
		
	    final Button button_start = (Button) findViewById(R.id.button_start);
	    final Button button_record = (Button) findViewById(R.id.button_record);
	    final Button button_stop = (Button) findViewById(R.id.button_stop);
	    
		button_start.setText("开始");	
		
		//监听开始按钮
        button_start.setOnClickListener(new OnClickListener(){

			public void onClick(View V)
	        {
				if(button_start.getText() == "开始") {
					mStart = true;
					mStartTime = System.currentTimeMillis();
				    button_start.setText("暂停");
				    button_record.setBackgroundResource(R.drawable.button_record_full);
				    button_stop.setBackgroundResource(R.drawable.button_stop_full);
				      
	      		    lastTime = 0;
				    recordTimes = 0;
				    linearLayout = (LinearLayout) findViewById(R.id.linearlayout1);
				    linearLayout.removeAllViewsInLayout();
	      		    mHandler.sendEmptyMessage(1);
	            }
				else if(button_start.getText() == "暂停"){
					mStart = false;
					tmpTime = System.currentTimeMillis();
					button_start.setText("继续");
					
					button_record.setBackgroundResource(R.drawable.button_record_half);
					mHandler.sendEmptyMessage(0);
				}
				else {
					mStart = true;
					long tmp = System.currentTimeMillis() - tmpTime;
					mStartTime = mStartTime + tmp;
					button_start.setText("暂停");
					button_record.setBackgroundResource(R.drawable.button_record_full);
					mHandler.sendEmptyMessage(1);
				}
	        }
	     });
        
        //监听停止按钮
        button_stop.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(button_start.getText() != "开始"){
					mStart = false;
					button_start.setText("开始");
					button_stop.setBackgroundResource(R.drawable.button_stop_half);
					button_record.setBackgroundResource(R.drawable.button_record_half);
					TextView textView1 = (TextView) findViewById(R.id.textView1);
					TextView textView2 = (TextView) findViewById(R.id.textView2);
					textView1.setText("00:00:00");
					textView2.setText("00");	
				}
			}
		});
        
        //监听记录按钮
        button_record.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(button_start.getText() == "暂停"){
					mIsRecorded = true;
					mHandler.sendEmptyMessage(1);
				}
			}
		});
	}
	
	//更新显示时间和显示记录的时间
	private void updateTime() {
		TextView textView1 = (TextView) findViewById(R.id.textView1);
		TextView textView2 = (TextView) findViewById(R.id.textView2);		
		currentTime = System.currentTimeMillis();
		long aTime = currentTime - mStartTime;
		StringBuilder[] sb1 = new StringBuilder[2];
 	    sb1[0] = new StringBuilder();
 	    sb1[1] = new StringBuilder();
		sb1 = getTimeFormat(aTime);
		String str;
		textView1.setText(sb1[0]);
		textView2.setText(sb1[1]);		
		
      	if(mIsRecorded) {
      		recordTimes++;
      		String rec;
      		long bTime;
      		if (recordTimes == 1) {
      			bTime = aTime;
      			
      		}
      		else {
			    bTime = currentTime - lastTime;
      		}
      		
      		StringBuilder[] sb2 = new StringBuilder[2];
     	    sb2[0] = new StringBuilder();
     	    sb2[1] = new StringBuilder();
    		sb2 = getTimeFormat(bTime);
    		if(recordTimes < 10)
    		{
    			rec = '0' + String.valueOf(recordTimes);
    		}
    		else {
    			rec = String.valueOf(recordTimes);
    		}
      		str = "<font color='orange'>" + rec + "</font>" + " <small>" + sb2[0].toString() +"." + sb2[1].toString() + "</small>" + " ";
      	    str += "<b>" + sb1[0].toString() + ".<small>" + sb1[1].toString() + "</small>" + "</b>";
      		CharSequence charSequence = Html.fromHtml(str);
      		
      	    TextView text1 = new TextView(this);
	        text1.setText(charSequence);
	        text1.setTextSize(23);
	        text1.setTextColor(Color.WHITE);
	        text1.setGravity(Gravity.CENTER);
	        AssetManager mgr=getAssets();//得到AssetManager
			Typeface tf=Typeface.createFromAsset(mgr, "fonts/lanting.TTF");//根据路径得到Typeface
			text1.setTypeface(tf);
	        
			TextView text2 = new TextView(this);
			text2.setText(" ");
			text2.setTextSize(10);
			linearLayout.addView(text2);
			linearLayout.addView(text1);
			 
			final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView1);
			Runnable mScrollToBottom = new Runnable() 
		    {   
		        @Override  
		        public void run()
		        {   
		            int off = linearLayout.getMeasuredHeight() - scrollView.getHeight();   
		            if (off > 0) 
		            {   
		            	scrollView.scrollTo(0, off);   
		            }                          
		        }   
		    }; 
		    mHandler.post(mScrollToBottom); 
	        mIsRecorded =false;
	      	lastTime = currentTime;
      	}
	}
	
	//把毫秒转为要显示的格式
	public StringBuilder[] getTimeFormat(long time) {
	    long tmp = time;
		time = time / 1000;
  	    int second = (int) (time % 60);
 	    int minute = (int) (time / 60) % 60;
 	    int hour = (int) (time / 3600);
 	    int minsecond = (int) (tmp / 10 % 100);
 	    StringBuilder[] sb = new StringBuilder[2];
 	    sb[0] = new StringBuilder();
 	    sb[1] = new StringBuilder();
 	   
 	    if(hour < 10) {
 	    	sb[0].append('0');
 	        sb[0].append(String.valueOf(hour));
 	    }
 	    else {
  		sb[0].append(String.valueOf(hour));
  	    }
  	    sb[0].append(':');
  	    if(minute < 10) {
  	    	sb[0].append('0');
  		    sb[0].append(String.valueOf(minute));
  		}
  	    else {
  		    sb[0].append(String.valueOf(minute));
  	    }
  	    sb[0].append(':');
  	    if(second < 10) {
  		    sb[0].append('0');
  		    sb[0].append(String.valueOf(second));
  	    }
  	    else {
  		sb[0].append(String.valueOf(second));
  	    }
  	    if(minsecond < 10) {
  	    	sb[1].append('0');
  	    	sb[1].append(minsecond);
  	    }
     	else {
     		sb[1].append(minsecond);
     	}
  	    return sb;
	}
	
	//监听返回键,实现点击返回键时弹出对话,连续两次点击退出
	@Override
	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			toast();
			return false;
		}
		else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 1) {
			MainActivity.this.finish(); 
		}
		return false;
	};
	
	/*protected void gialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setTitle("提示");
		builder.setMessage("确定要退出吗?");
		builder.setPositiveButton("确认", 
                new android.content.DialogInterface.OnClickListener() { 
                    @Override
                    public void onClick(DialogInterface dialog, int which) { 
                        dialog.dismiss(); 
                        MainActivity.this.finish(); 
                    } 
                }); 
        builder.setNegativeButton("取消", 
                new android.content.DialogInterface.OnClickListener() { 
                    @Override
                    public void onClick(DialogInterface dialog, int which) { 
                        dialog.dismiss(); 
                    } 
                }); 
        builder.create().show(); 
	}*/
	
	protected void toast() {
		Timer tExit = null;
		if (isExit == false) {
		isExit = true; // 准备退出
		Toast textToast = Toast.makeText(this, "小样!想退出?!", Toast.LENGTH_LONG);
		textToast.show();
		tExit = new Timer();
	    tExit.schedule(new TimerTask() {
	    	@Override
		    public void run() {
		    isExit = false; // 取消退出
		    }
		    }, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务
		 } 
		else {
			finish();
		    System.exit(0);
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}

        布局文件的代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:src="@drawable/backguand_new" 
        android:scaleType="fitCenter"/>

    <Button
        android:id="@+id/button_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="12dp"
        android:text="开始"
        android:textColor="#ffffff" 
        android:background="@drawable/button_start_full"/>

    <Button
        android:id="@+id/button_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button_start"
        android:layout_alignBottom="@+id/button_start"
        android:layout_marginLeft="29dp"
        android:layout_toRightOf="@+id/button_start"
        android:background="@drawable/button_stop_half"
        android:text="停止"
        android:textColor="#ffffff" />

    <Button
        android:id="@+id/button_record"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button_start"
        android:layout_alignBottom="@+id/button_start"
        android:layout_marginRight="28dp"
        android:layout_toLeftOf="@+id/button_start"
        android:background="@drawable/button_record_half"
        android:text="记录"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button_start"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:src="@drawable/showrecord_new" />

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="wrap_content"
        android:layout_height="340dp"
        android:layout_alignLeft="@+id/imageView2"
        android:layout_alignRight="@+id/imageView2"
        android:layout_alignTop="@+id/imageView2" 
        android:scrollbars="none">

        <LinearLayout
            android:id="@+id/linearlayout1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_toRightOf="@+id/textView1"
        android:text="00" 
        android:textColor="#ffffff"
        android:textSize="40dp"/>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView2"
        android:layout_marginBottom="5dp"
        android:layout_alignLeft="@+id/imageView2"
        android:text="00:00:00"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ffffff"
        android:textSize="60dp" />

</RelativeLayout>
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值