Android - 获取计时器小部件的时间

时间:2009-02-08 22:23:17

标签: android time view widget chronometer

如何从计时器中获取时间?我尝试过getText,getFormat,getBase等,但是没有一个可以工作。

示例代码段:

Chronometer t = (Chronometer)findViewById(R.id.toptime);
long time = SystemClock.elapsedRealtime()-t.getBase();
Log.d(null,"Was: "+time); //time is not the proper time for some reason - it is a random number between 0 and 50
t.setBase(SystemClock.elapsedRealtime());
t.start();

7 个答案:

答案 0 :(得分:99)

如果你看一下Chronometer类的来源,你会发现它没有在一个字段中存储经过的时间,并且每次需要更新显示时都会在内部计算它。

然而,在您自己的代码中执行相同操作相对容易:

long elapsedMillis = SystemClock.elapsedRealtime() - chronometerInstance.getBase();

这假设你已经开始了这样的事情:

chronometerInstance.setBase(SystemClock.elapsedRealtime());
chronometerInstance.start();

以下是一个完整的例子:

public class ChronoExample extends Activity {
Chronometer mChronometer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    mChronometer = new Chronometer(this);
    layout.addView(mChronometer);

    Button startButton = new Button(this);
    startButton.setText("Start");
    startButton.setOnClickListener(mStartListener);
    layout.addView(startButton);

    Button stopButton = new Button(this);
    stopButton.setText("Stop");
    stopButton.setOnClickListener(mStopListener);
    layout.addView(stopButton);

    Button resetButton = new Button(this);
    resetButton.setText("Reset");
    resetButton.setOnClickListener(mResetListener);
    layout.addView(resetButton);        

    setContentView(layout);
}

private void showElapsedTime() {
    long elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase();            
    Toast.makeText(ChronoExample.this, "Elapsed milliseconds: " + elapsedMillis, 
            Toast.LENGTH_SHORT).show();
}

View.OnClickListener mStartListener = new OnClickListener() {
    public void onClick(View v) {
        mChronometer.start();
        showElapsedTime();
    }
};

View.OnClickListener mStopListener = new OnClickListener() {
    public void onClick(View v) {
        mChronometer.stop();
        showElapsedTime();
    }
};

View.OnClickListener mResetListener = new OnClickListener() {
    public void onClick(View v) {
        mChronometer.setBase(SystemClock.elapsedRealtime());
        showElapsedTime();
    }
};
}

关于天文台表的一个有点令人困惑的事情是你无法真正将它用作秒表,它可以再次启动,停止和重新启动。当它正在运行时,它将始终显示自您上次重置它以来经过的时间,无论多少次以及您在此期间停止了多长时间。当它停止时,它只是停止更新显示。

如果您需要类似秒表的东西,则必须使用Chronometer子类或使用source创建自己的版本。

alt text

答案 1 :(得分:12)

我发现这个例子非常有用,感谢nyenyec!

这是关于如何将其变成真正的秒表功能的两分钱,没有子类计时器。只需更改mStartListener方法来解析mChronometer中的文本(毕竟它是从TextView派生的),计算毫秒数,并使用setBase()将基准时间重新调整为过去的那段时间:

  View.OnClickListener mStartListener = new OnClickListener() {
    public void onClick(View v) {

      int stoppedMilliseconds = 0;

      String chronoText = mChronometer.getText().toString();
      String array[] = chronoText.split(":");
      if (array.length == 2) {
        stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 1000
            + Integer.parseInt(array[1]) * 1000;
      } else if (array.length == 3) {
        stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 60 * 1000 
            + Integer.parseInt(array[1]) * 60 * 1000
            + Integer.parseInt(array[2]) * 1000;
      }

      mChronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
      mChronometer.start();
    }
  };

答案 2 :(得分:3)

@nyenyec +1:这是我最终的结果,同时在没有子类的情况下使用nyenyec的响应。

        chronometer.setOnChronometerTickListener(new OnChronometerTickListener() {                      
        @Override
        public void onChronometerTick(Chronometer chronometer) {
            long elapsedMillis = SystemClock.elapsedRealtime() - chronometer.getBase();
            if(elapsedMillis>THRESHOLD){
                doYourStuff();
            }
        }
    });

THRESHOLD是

private static final int THRESHOLD_EXERSISE = 60000; //In milliseconds

答案 3 :(得分:2)

我的解决方案:

    public void starttimer(View view){
    Button mybtn = (Button) view;
    if (mybtn.equals(findViewById(R.id.button1))) {
        mycm.setBase(SystemClock.elapsedRealtime() - elapsed);
        mycm.start();
    }
    else {
        mycm.stop();
        elapsed = SystemClock.elapsedRealtime() -  mycm.getBase();
    }
}

on onCreate:

    mycm = (Chronometer) findViewById(R.id.chronometer1);
    elapsed = 0;

布局中有两个按钮,它们都调用starttimer方法(启动和停止)

答案 4 :(得分:2)

有些迟到的回应,但我今天试图自己解决这个问题。我最后只是解析了视图的文本:

    // Expects a string in the form MM:SS or HH:MM:SS
public static int getSecondsFromDurationString(String value){

    String [] parts = value.split(":");

    // Wrong format, no value for you.
    if(parts.length < 2 || parts.length > 3)
        return 0;

    int seconds = 0, minutes = 0, hours = 0;

    if(parts.length == 2){
        seconds = Integer.parseInt(parts[1]);
        minutes = Integer.parseInt(parts[0]);
    }
    else if(parts.length == 3){
        seconds = Integer.parseInt(parts[2]);
        minutes = Integer.parseInt(parts[1]);
        hours = Integer.parseInt(parts[0]);
    }

    return seconds + (minutes*60) + (hours*3600);
}

所以用view.getText()。toString()调用getSecondsFromDurationString会给你总的经过时间(以秒为单位)(我的应用程序是某种秒表,所以你可以暂停并恢复它)。

希望它有所帮助。

答案 5 :(得分:0)

    final Chronometer counter = (Chronometer) findViewById(R.id.chronometer1);
    counter.setOnChronometerTickListener(new OnChronometerTickListener() {

        public void onChronometerTick(Chronometer chronometer) {
            // TODO Auto-generated method stub
            chronometer.refreshDrawableState();

        }
    });

    final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton1);
    togglebutton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Perform action on clicks
            if (togglebutton.isChecked()) {
                counter.start();
            } else {
                counter.stop();
            }
        }
    });

答案 6 :(得分:0)

//ok here is the final changed code which works well

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.Toast;

public class HelloWidgetActivity extends Activity {
    Chronometer mChronometer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        mChronometer = new Chronometer(this);
        layout.addView(mChronometer);

        Button startButton = new Button(this);
        startButton.setText("Start");
        startButton.setOnClickListener(mStartListener);
        layout.addView(startButton);

        Button stopButton = new Button(this);
        stopButton.setText("Stop");
        stopButton.setOnClickListener(mStopListener);
        layout.addView(stopButton);

        Button resetButton = new Button(this);
        resetButton.setText("Reset");
        resetButton.setOnClickListener(mResetListener);
        layout.addView(resetButton);

        setContentView(layout);
    }

    private void showElapsedTime() {
        long elapsedMillis = SystemClock.elapsedRealtime()
                - mChronometer.getBase();
        Toast.makeText(HelloWidgetActivity.this,
                "Elapsed milliseconds: " + elapsedMillis, Toast.LENGTH_SHORT).show();
    }



    View.OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
          int stoppedMilliseconds = 0;
          String chronoText = mChronometer.getText().toString();
          String array[] = chronoText.split(":");
          if (array.length == 2) {
            stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 1000
                + Integer.parseInt(array[1]) * 1000;
          } else if (array.length == 3) {
            stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 60 * 1000 
                + Integer.parseInt(array[1]) * 60 * 1000
                + Integer.parseInt(array[2]) * 1000;
          }
          mChronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
          mChronometer.start();
        }
      };

    View.OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.stop();
            showElapsedTime();
        }
    };

    View.OnClickListener mResetListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.setBase(SystemClock.elapsedRealtime());
            mChronometer.stop();
            showElapsedTime();
        }
    };
}