Only the original thread that created a view hierarchy can touch its views(只有创建视图层次结构的原始线程才能接触其视图)
问题描述
我正在尝试让 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.
这是我的代码:
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?
推荐答案
TickClass
中的代码在另一个线程上运行.要从这里进行 UI 工作,请使用 runOnUiThread
.有关详细信息,请参阅 文档.
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));
}
});
这篇关于只有创建视图层次结构的原始线程才能接触其视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:只有创建视图层次结构的原始线程才能接触其视图
基础教程推荐
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01