首页 > 解决方案 > 如何修复错误“只有创建视图层次结构的原始线程才能触及其视图。”

问题描述

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

我尝试使用处理程序和 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,并且我希望每秒更改一次。

标签: javaandroidandroid-studio

解决方案


在你的 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);
  }
}

推荐阅读