gpt4 book ai didi

javascript - 如何使用 WebAppInterface(Javascript 接口(interface))操作 Android View ?

转载 作者:行者123 更新时间:2023-12-03 07:42:41 27 4
gpt4 key购买 nike

当我的 Android WebView 运行时,我使用 WebAppInterface 从 Javascript 获取数据。从 Javascript 获取一些数据后,如何立即操作 Android View ?

public class WebAppInterface {
Context mContext;

/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}

//This function can only be called by javascript
@android.webkit.JavascriptInterface
public void sendDataToJava(float currTime, String url) {

videoUrl = url;
videoTime = Math.round(currTime);

//use references to views to change stuff
videoView.seekTo(videoTime); //ERROR HERE
//ERROR: Only the original thread that created a view hierarchy can touch its views


}


}

最佳答案

您需要保留对 View 包含 Activity 的引用,并使用可运行的 Activity.runOnUiThread 方法调用与 View 相关的代码。

它看起来像这样:

public class WebAppInterface {
Context mContext;
Activity mActivity;

/** Instantiate the interface and set the context */
WebAppInterface(Context c, Activity a) {
mContext = c;
mActivity = a;

}

//This function can only be called by javascript
@android.webkit.JavascriptInterface
public void sendDataToJava(float currTime, String url) {

videoUrl = url;
videoTime = Math.round(currTime);

mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
videoView.seekTo(videoTime);
}
});
}

}

关于javascript - 如何使用 WebAppInterface(Javascript 接口(interface))操作 Android View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35343995/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com