0

我创建了一个自定义 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;
        }
    });
}

第 55 行是 galleryView.this.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);

我应该怎么做才能避免这个问题?

4

1 回答 1

1

您正在尝试从活动 UI 线程以外的其他线程更新 UI。

就像错误说的:

Only the original thread that created a view hierarchy can touch its views.

尝试用runOnUIThread(new Runnable{ ... }())

示例:我可以举一个使用 runOnUiThread 显示 toast 的示例吗?

于 2013-02-23T21:52:18.357 回答