1

HTML:

<a href="javascript:AndroidFunction.xxxx()">xxxx</a>

活动:

public class MainActivity extends Activity
    {
    @Override
    protected void onCreate(Bundle savedInstanceState)
            {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        

        WebView webview = (WebView) findViewById(R.id.webview);
        final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
        webview.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
        webview.getSettings().setJavaScriptEnabled(true); 
        webview.loadUrl("file:///android_asset/x1.html");        
    }

    public class MyJavaScriptInterface {
        Context mContext;

        MyJavaScriptInterface(Context c) {
            mContext = c;
        }

        public void xxxx()
        {
            setContentView(R.layout.x);              
        }
    }
}

我得到这个错误:

未捕获的处理程序thread WebViewCoreThread exiting due to uncaught exception android.view.ViewRoot$CalledFromWrongThreadException::

只有创建视图层次结构的原始线程才能接触其视图。

请帮帮我。

4

3 回答 3

0

一方面,你不应该setContentView从任何地方打电话,但onCreate. 如果要更改Views,请在布局层次结构中开始新的Activity或添加/更新Views。

此外,这CalledFromWrongThreadException意味着您在不在 UI 线程上时尝试编辑Views,这是不允许的(出于我现在不会讨论的原因)。我建议您使用在 UI 线程上View.post(Runnable action)进行编辑。View对这个问题的回答应该对你有所帮助。

于 2013-04-25T17:22:40.490 回答
0

尝试

public void xxxx() {
    runOnUiThread(new Runnable() {
        public void run() {
           setContentView(R.layout.x);              
        }
    });
}
于 2013-04-25T17:44:29.600 回答
-1

ause: This error is common if you tried to send UI events to the UI thread from outside the UI thread. The test method Thread tried to interact with the UI outside the UI thread.

Suggested: Use Handler to solve the cause.

Solution: Link

于 2013-09-19T15:40:53.330 回答