我有一个需要调整的工作应用。我正在努力让标签更新每一个' n'秒使用postDelayed方法,但我只是让它延迟它第一次显示的时间,而不是经常更新标签。我已尝试过多种方法在PostDelayed中使用Runnable方法,但我还没有做任何事情,除了再次推迟初始帖子。我将不胜感激任何有关如何使其发挥作用的反馈或建议。 " textLightReading.setText"是我试图延迟更新的标签。
`@Override
public void onSensorChanged(final SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
final Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mHandler.postDelayed(this, 1000);
final float lux = event.values[0];
final float conversion = Math.round(((1/638f) * lux) * 100.0f)/100.0f;
textLightReading.setText("Light: " + conversion);
}
}, 1000);
}
}`
这是另一种尝试......
`@Override
public void onSensorChanged(final SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
float lux = event.values[0];
final float conversion = Math.round(((1/638f) * lux) * 100.0f)/100.0f;
final Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
textLightReading.setText("Light: " + conversion);
//mHandler.postDelayed(this, 1000);
}
}, 1000);
}
}`
我确信我不明白如何使用它。再次感谢。
答案 0 :(得分:0)
试试这个 第一种方法
Handler mHandler = new Handler();
float lux,conversion;// intialize it
Runnable run=new Runnable() {
@Override
public void run() {
textLightReading.setText("Light: " + conversion);
//Line to kill runnable before a new one starts
mHandler.removeCallbacks(run);
}
};
//it will update 1 second after onSensorChanged called and when condition true
//As per your both attempts
@Override
public void onSensorChanged(final SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
lux = event.values[0];
conversion = Math.round(((1/638f) * lux) * 100.0f)/100.0f;
mHandler.postDelayed(run, 1000);
}
}
如果onSensorChanged调用了
,那么每隔'n'秒更新标签就无关紧要了第二种方法第1部分: //使用计时器
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(run);
}
}, 500, 500); //put this onCreateView or at initialization
注意:当不再需要计时器时,用户应该调用cancel,这会释放计时器的线程和其他资源。未明确取消的计时器可能无限期地保留资源。
第二种方法第2部分:在你的问题中提到类似方法
Handler mHandler = new Handler();
Runnable run=new Runnable() {
@Override
public void run() {
textLightReading.setText("Light: " + conversion); //update textView
mHandler.postDelayed(run, 1000);
}
};
mHandler.post(run); // at initialization or anywhere in your code where you want to start handler
@Override
public void onSensorChanged(final SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
lux = event.values[0];
conversion = Math.round(((1/638f) * lux) * 100.0f)/100.0f;
}
}
还有很多其他方法可以做到这一点......