【问题标题】:Only the original thread that created a view hierarchy can touch its views只有创建视图层次结构的原始线程才能接触其视图
【发布时间】:2012-12-26 23:41:12
【问题描述】:

我正在尝试让 ImageView 在我的可绘制文件夹中的 2 个图像之间进行动画处理。

我以为一切都会正常,但日志显示错误:Only the original thread that created a view hierarchy can touch its views.

这是我的代码:

public class ExerciseActivity extends Activity {
    private ExercisesDataSource datasource;
    private Cursor cursor;
    private ImageView image_1_view;
    private Timer _timer;
    private int _index;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise);     

        datasource = new ExercisesDataSource(this);
        datasource.open();

        cursor = datasource.fetchExercise(exerciseDataID);

        image_1_view = (ImageView) findViewById(R.id.exercise_image);

        _index = 1;
        _timer = new Timer();
        _timer.schedule(new TickClass(), 1000);

    }

    public class TickClass extends TimerTask
    {
        private int columnIndex;

        @Override
        public void run() {
            if (_index == 1) {
                columnIndex = cursor.getColumnIndex(MySQLiteHelper.COLUMN_IMAGE_1);
                _index = 2;
            }
            else {
                columnIndex = cursor.getColumnIndex(MySQLiteHelper.COLUMN_IMAGE_2);
                _index = 1; 
            }   

            String image_1 = cursor.getString(columnIndex);
            image_1 = image_1.replace(".png", "");
            int resourceId = getResources().getIdentifier(getPackageName() + ":drawable/" + image_1, null, null);
            image_1_view.setImageDrawable(getResources().getDrawable(resourceId));
        }
    }
}

我继续将类和函数设置为公开,但这并没有解决问题。

所有资源和一切都很好,我该如何解决这个错误?

【问题讨论】:

标签: android imageview


【解决方案1】:

TickClass 中的代码在另一个线程上运行。要从这里进行 UI 工作,请使用 runOnUiThread。 详情请见docu

runOnUiThread(new Runnable() {
    public void run() {
        image_1_view.setImageDrawable(getResources().getDrawable(resourceId));
    }
});

【讨论】:

  • 你如何在片段上执行此操作?
  • 以及如何在一个简单的类中做到这一点
  • @AlexanderMladzhov 它是Activity 的一个方法,所以你需要一个Activity的引用来调用它。或者,您可以使用Handler,就像 Nicklas Gnejs Eriksson 的回答一样。
【解决方案2】:

您应该使用处理程序。 http://developer.android.com/reference/android/os/Handler.html

在 onCreate 中创建处理程序。然后将处理程序与另一个线程一起使用。 将代码封装在帖子中,此代码将在 UI 线程上执行,这可能会更改 UI 组件。

"public final boolean post (Runnable r) 在 API 级别 1 中添加

使 Runnable r 添加到消息队列中。 runnable 将在附加此处理程序的线程上运行。”

    handler.post( new Runnable() {

        @Override
        public void run() {
            image_1_view.setImageDrawable(getResources().getDrawable(resourceId));
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多