java - 如何修复错误“只有创建视图层次结构的原始线程才能触及其视图。”
问题描述
我想每秒刷新屏幕上的计时器。我收到此错误,无法修复。
我尝试使用处理程序和 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);
}
});
我希望在没有任何错误的情况下更改视图和 UI,并且我希望每秒更改一次。
解决方案
在你的 UI 中使用postDelayed()
一些。View
此示例活动Toast
每 5000 毫秒显示一次:
/***
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);
}
}
推荐阅读
- .net - MySQL服务器安装指南
- png - 如何将 PNG 文件的签名更改为“未损坏”?
- amazon-web-services - 如何使用 CloudFormation 创建具有集成 RDS 的 AWS Elasticbeanstalk 应用程序?
- c - 如何存储一个字符串数组以便以后可以引用它?
- database - How to generate sql col with binary function in DolphinDB script?
- c# - UWP - 如何在 C# 中使用 OneDrive API 同步文件
- python - Pandas:仅当时间戳大于另一列的时间戳时才获取一列的累积总和
- javascript - Button wont call a function in JavaScript?
- isabelle - Isabelle/HOL 中的 thy_goal_defn 和关键字
- javascript - React.js PWA 中桌面和移动设备的分离设计