我創建了一個自定義 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();
這個不需要