我想每秒刷新屏幕上的计时器。我收到此错误并且无法修复它。
我尝试使用处理程序和 runOnUiThreat 但没有成功。
runOnUiThread(new Runnable() {
@Override
public void run() {
final Timer txtRefresher = new Timer();
txtRefresher.schedule(new TimerTask() {
@Override
public void run() {
timerConfirmation.setText(String.format("%d", timer));
if (timer == 0) {
txtRefresher.cancel();
}
}
}, 199, 60000);
}
});
我希望更改 View 和 UI 而不会出现任何错误,并且我希望每秒都更改它。
最佳答案
在 UI 中的某些 View
上使用 postDelayed()
。此示例 Activity 每 5000 毫秒显示一次 Toast
:
/***
Copyright (c) 2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.post;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class PostDelayedDemo extends Activity implements Runnable {
private static final int PERIOD=5000;
private View root=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
root=findViewById(android.R.id.content);
}
@Override
public void onStart() {
super.onStart();
run();
}
@Override
public void onStop() {
root.removeCallbacks(this);
super.onStop();
}
@Override
public void run() {
Toast.makeText(PostDelayedDemo.this, "Who-hoo!", Toast.LENGTH_SHORT)
.show();
root.postDelayed(this, PERIOD);
}
}
关于java - 如何修复错误 "Only the original thread that created a view hierarchy can touch its views.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56719531/