我想在应用屏幕上的标签中显示当前时间(小时:分钟)。
是否可以随着时间的变化自动更新? 我的意思是,当分钟(和/或小时)改变时,我希望文本/标签自动更改它的值,而不必总是检查当前时间并更新它。
有人知道这是否可行吗?就像 Android API 中有一个特殊的“时间”对象可以连续显示它一样吗?
谢谢。
编辑:如果我想要的不可能,你能建议我一个精心设计的手动执行选项吗?
最佳答案
Does anyone know if this is possible? Like if there's a special "time" object from the Android API that displays it continuously?
没有内置的东西,就像其他人所说的那样,您将使用 Handler
并自己更新时间。请参阅下面的一个小示例:
private Handler mHandler = new Handler();
private TextView mText;// the TextView
private int mHour, mMinute; // variables holding the hour and minute
private Runnable mUpdate = new Runnable() {
@Override
public void run() {
mMinute += 1;
// just some checks to keep everything in order
if (mMinute >= 60) {
mMinute = 0;
mHour += 1;
}
if (mHour >= 24) {
mHour = 0;
}
// or call your method
mText.setText(mHour + ":" + mMinute);
mHandler.postDelayed(this, 60000);
}
};
@Override
protected void onResume() {
super.onResume();
// whenever the activity is built or resumed update the time and start posting updates
Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
mText.setText(mHour + ":" + mMinute);
mHandler.postDelayed(mUpdate, 60000); // 60000 a minute
}
@Override
protected void onStop() {
super.onStop();
mHandler.removeCallbacks(mUpdate);// we need to remove our updates if the activity isn't focused(or even destroyed) or we could get in trouble
}
您可以调用您的方法,而不是 Runnable
中的 setText()
部分。
关于Android标签具有自动更新时间(小时和分钟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17502492/