我使用WebAppInterface在我的Android WebView运行时从Javascript中获取数据。在从Javascript中获取一些数据后,如何操纵我的Android视图?
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
}
}
答案 0 :(得分:1)
您需要保持对包含活动的视图的引用,并使用activity.runOnUiThread方法使用runnable调用与视图相关的代码。
它看起来像这样:
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);
}
});
}
}