只有创建一个视图层次可以触摸其观点原来的线程视图、线程、创建一个、层次

2023-09-05 07:03:23 作者:乜許。迩吥嬞

我想获得的ImageView在我的绘制文件夹2图像之间的动画。

I'm trying to get an ImageView to animate between 2 images in my drawable folder.

我以为一切会正常工作,但在日志中显示错误:只有创建视图层次可以触摸其观点原来的线程

I thought everything would work fine, but the log is showing an error: Only the original thread that created a view hierarchy can touch its views.

这是我的code:

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));
        }
    }
}

我继续设置类和函数的公共但是这并没有解决它。

I went ahead and set the classes and functions to public but that did not fix it.

所有的资源,一切都很好,我该如何解决这个问题?

All of the resources and everything are fine, how do I fix this error?

推荐答案

您$ C $在 TickClass C同时运行在另一个线程。从这里做UI工作中使用 runOnUiThread 。 请参阅docu了解详细信息。

Your code in TickClass runs on another thread. To do UI work from here use runOnUiThread. See the docu for details.

runOnUiThread(new Runnable() {
    public void run() {
        image_1_view.setImageDrawable(getResources().getDrawable(resourceId));
    }
});
 
精彩推荐
图片推荐