java - 如何修复错误 "Only the original thread that created a view hierarchy can touch its views."

标签 java android android-studio

我想每秒刷新屏幕上的计时器。我收到此错误并且无法修复它。

我尝试使用处理程序和 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/

相关文章:

android-studio - 如何在 Android Studio 2.4 中截取设备截图

为创建 AD 帐户编写了 Java 代码,但发生 LDAP 异常

java - 无法理解 : @EnableWebMvc and <annotation-driven/> 之间的行为差​​异

java - ((LocalBinder)service) 是什么意思?

java - 禁用按钮一段时间

android - 如何确定哪个应用程序导致 “Screen Overlay Detected” 错误?

java - 如何将 android 项目作为库导入而不是将其编译为 apk (Android studio 1.0)

java - 如何编写脚本/代码来阻止 apache kafka 消费者消费消息?

android - 当前提供的android模拟器是否能够模拟传感器?

java - 如何将 fragment 添加到 fragment 事务中?