访问UI从JavaScript在Android [英] Access UI from JavaScript on Android

查看:160
本文介绍了访问UI从JavaScript在Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一些原因,我不得不使用的WebView在我的Andr​​oid应用程序和业务逻辑的一部分被包含在JavaScript中(我运行它使用addJavascriptInterface())。问题是,我无法从绑定到脚本对象修改我的应用程序的UI组件。这是在文档中解释说:

For some reasons I have to use WebView in my Android application and part of business logic is contained in JavaScript (I run it using addJavascriptInterface()). The problem is that I can't modify the UI components of my application from object bound to the script. That's explained in the documentation:

注:绑定到你的JavaScript对象在另一个运行
  在它构建线程线程,而不是

Note: The object that is bound to your JavaScript runs in another thread and not in the thread in which it was constructed.

我不知道是否有一些绕过这个问题?

I'm wondering if there is some workaround for this problem?

推荐答案

您需要通过处理程序实例​​到你的JavaScript接口,并用它来发布有可运行。如果这个处理器将在UI线程创建,可运行<一个href=\"http://developer.android.com/reference/android/os/Handler.html#post%28java.lang.Runnable%29\">posted有也将在UI线程调用。

You need to pass Handler instance to your JavaScript interface and use it to post runnables there. If this handler will be created on UI thread, runnables posted there will also be invoked on the UI thread.

Handler mHandler = new Handler(); // must be created on UI thread, e.g. in Activity onCreate

// from javascript interface...
mHandler.post(new Runnable() {
    @Override
    public void run() {
        // code here will run on UI thread
    }
});

另一个解决方法是使用活动的方法<一href=\"http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29\">runOnUIThread

mActivity.runOnUIThread(new Runnable() {
    @Override
    public void run() {
       // code here will run on UI thread
    }
});

这篇关于访问UI从JavaScript在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆