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

发布于 2024-07-13 04:42:04 字数 386 浏览 10 评论 0原文

如何从天文台表获取时间? 我尝试了 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();

How to get the time from a Chronometer? I tried getText, getFormat, getBase, etc, but none of them could work.

Example code snippet:

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();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

赤濁 2024-07-20 04:42:04

如果您查看 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 的一个有点令人困惑的事情是,你不能真正将它用作秒表,开始、停止并再次重新启动。 当它运行时,它将始终显示自您上次重置以来所经过的时间,无论您在此期间停止了多少次和多长时间。 当它停止时,它只是停止更新显示。

如果您需要像秒表这样的东西,您必须对 Chronometer 进行子类化,或者使用 来源

替代文字

If you look at the source of the Chronometer class, you'll see that it doesn't store the elapsed time in a field and it calculates it internally every time it needs to update the display.

However it's relatively easy to do the same in your own code:

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

This assumes that you have started your clock something like this:

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

Here's a full example:

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();
    }
};
}

One somewhat confusing thing about Chronometer is that you can't really use it as a stopwatch that gets started, stopped and restarted again. When it's running, it will always show the time elapsed since you last reset it, no matter how many times and for how long you have stopped it in the meantime. When it is stopped, it simply stops updating the display.

If you need something like a stopwatch you'll have to subclass Chronometer or maybe create your own version using the source.

alt text

情丝乱 2024-07-20 04:42:04

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

这是我关于如何将其变成真正的秒表功能而不需要子类化 Chronometer 的两分钱。 只需更改 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();
    }
  };

I found this example really useful, thanks nyenyec!

Here's my two cents on how to turn it into a real stopwatch function, without subclassing Chronometer. Just change the mStartListener method to parse the text from mChronometer (it's derived from TextView after all), calculate milliseconds, and use setBase() to readjust the base time to that amount of time in the past:

  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();
    }
  };
奢望 2024-07-20 04:42:04

@nyenyec +1:这就是我最终得到的结果,同时使用没有子类的 nyenyec 的响应。

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

其中阈值是

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

@nyenyec +1: here is what i ended up with, while using nyenyec's response without a sub class.

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

where THRESHOLD is

private static final int THRESHOLD_EXERSISE = 60000; //In milliseconds
肩上的翅膀 2024-07-20 04:42:04

回复有点晚了,但我今天想自己解决这个问题。 我最终只是解析了视图的文本:

    // 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 可以为您提供以秒为单位的总运行时间(我的应用程序是某种秒表,因此您可以暂停并恢复它)。

希望能帮助到你。

Somewhat late response, but I was trying to solve this myself today. I ended up just parsing the text of the view:

    // 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);
}

So calling getSecondsFromDurationString with view.getText().toString() gives you the total elapsed time in seconds (my application is some kind of stop watch, so you can pause it and resume it).

Hope it helps.

薯片软お妹 2024-07-20 04:42:04

我的解决方案:

    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();
    }
}

在onCreate中:

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

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

My Solution:

    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();
    }
}

In onCreate:

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

There are two buttons in the layout which both call the starttimer method (start and stop)

空袭的梦i 2024-07-20 04:42:04
    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();
            }
        }
    });
    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();
            }
        }
    });
笑,眼淚并存 2024-07-20 04:42:04
//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();
        }
    };
}
//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();
        }
    };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文