2017-08-18 63 views
0

總之,我將如何檢索時間並將其顯示在其他地方的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"/> 

回答

0

我想通了。點擊後,您必須調用文本視圖並在其中設置文本。

下面是在問題中提供的代碼工作的例子,在加上它的點擊方法:

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