问题描述
- onKeyDown() 不能在继承类上运行
-
我创建了一个自定义 GalleryView,在 Samsung Galaxy S III 或者 Nexus 4 上都可以执行。当我在模拟器中运行的时候,出现下面的错误:02-24 01:01:03.593: E/AndroidRuntime(3429): FATAL EXCEPTION: Thread-11 02-24 01:01:03.593: E/AndroidRuntime(3429): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 02-24 01:01:03.593: E/AndroidRuntime(3429): at android.view.ViewRoot.checkThread(ViewRoot.java:2802) 02-24 01:01:03.593: E/AndroidRuntime(3429): at android.view.ViewRoot.playSoundEffect(ViewRoot.java:2581) 02-24 01:01:03.593: E/AndroidRuntime(3429): at android.view.View.playSoundEffect(View.java:8516) 02-24 01:01:03.593: E/AndroidRuntime(3429): at android.widget.Gallery.onKeyDown(Gallery.java:1109) 02-24 01:01:03.593: E/AndroidRuntime(3429): at com.example.coverflow.ui.galleryView$1.run(galleryView.java:55) 02-24 01:01:03.593: E/AndroidRuntime(3429): at java.lang.Thread.run(Thread.java:1096)
这些错误涉及到下面的代码:
public void startSlideShow(final int periodTime) { final Runnable __runnable = new Runnable() { @Override public void run() { if (!isTouched) galleryView.this.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null); mHandler.postDelayed(this, periodTime); } }; new Thread(__runnable).start(); this.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { int currentEvent = event.getAction(); if (currentEvent == MotionEvent.ACTION_DOWN || currentEvent == MotionEvent.ACTION_MOVE) isTouched = true; else { isTouched = false; // Reset handler mHandler.removeCallbacks(__runnable); mHandler.postDelayed(__runnable, periodTime); } return false; } }); }
如何处理这个问题?
Line 55 是
galleryView.this.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
解决方案
galleryView.this.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
你这一句是在你自己new的thread里面执行的。所以会报错。
用
mHandler.post(__runnable);
new Thread(__runnable).start();
这个不需要
解决方案二:
你可以从其他线程中更新 UI,而不是activity UI 线程。
就比如错误提示:
Only the original thread that created a view hierarchy can touch its views.
使用 runOnUIThread(new Runnable{ ... }()) 将文件访问代码打包
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();
}
});
}
}
时间: 2024-10-29 22:56:02