onKeyDown()不适用于扩展类

时间:2013-02-23 21:46:47

标签: android

我创建了一个自定义GalleryView,它适用于我的设备(三星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);

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

1 个答案:

答案 0 :(得分:1)

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

如错误所示:

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

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

包装文件访问代码

示例:Can i have an example of displaying a toast using runOnUiThread.