如何在秒表上检索当前时间?

时间:2017-08-18 15:55:26

标签: java android textview

简而言之,我如何检索时间并在其他地方的Textview上显示它?就像停止观看研磨的变体一样,当计时器停止时会自动更新某些视图?

如果您了解正确研磨的任何资源或android studio time tracking features的其他示例,请加入它们。

这是一些工作。 java停止观看代码:

package com.example.temp1.stackoverflowquestion;

import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


//Timer Text and Button
TextView txtTimer;
Button btn;

//Stop Watch logic
Handler handler;
long StartTime,timeInMilliseconds,TimeBuff,UpdateTime =0L;
int Seconds, Minutes, MilliSeconds;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtTimer = (TextView) findViewById(R.id.Timer_Value);
    btn = (Button)findViewById(R.id.btnStart_Stop);
    btn.setText("Start");
    handler = new Handler() ;

    //start/stop timer and change text
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (btn.getText().toString() == "Start") {

                btn.setText("Stop");
                StartTime = SystemClock.uptimeMillis();
                handler.postDelayed(runnable, 0);
            } else {
                btn.setText("Start");
                TimeBuff += timeInMilliseconds;
                handler.removeCallbacks(runnable);
            }
        }
    });

}

//Stop Watch logic
public  Runnable runnable = new Runnable() {
    @Override
     public void run() {
         timeInMilliseconds = SystemClock.uptimeMillis()-StartTime;
         UpdateTime = TimeBuff+timeInMilliseconds;
         Seconds=(int)(UpdateTime/1000);
         Minutes=Seconds/60;
         Seconds%=60;
         MilliSeconds=(int)(UpdateTime%1000);
         txtTimer.setText(""+Minutes+":"
         +String.format("%02d",Seconds)+":"
         +String.format("%03d",MilliSeconds));
         handler.postDelayed(this,0);
    }

};
}

这里是.xml布局代码:

    <TextView
        android:id="@+id/Timer_Value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textColor="#000"
        android:layout_margin="20dp"
        android:text="00:00:00"
        android:textSize="50sp"/>

        <Button
            android:id="@+id/btnStart_Stop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"/>

1 个答案:

答案 0 :(得分:0)

我明白了。单击时,您必须调用文本视图并在其中设置文本。

以下示例适用于问题中提供的代码,并在点击方法中添加:

txtView.setText(txtTimer.getText().toString());