0

是否可以使用私有内部类作为 Javascript 接口WebView

public class WebController{

    private WebView wv;
    public WebController(WebView wv){
        this.wv=wv;
        this.wv.addJavascriptInterface(new JSInterface(), "Android");
    }

    private class JSInterface{

        void someMethod(){ /* ... */ }        

    }

}
4

2 回答 2

0

是的,可以使用私有内部类作为 jsInterface,如下所示:

public class JavascriptInterfaceActivity extends Activity {
    /** Called when the activity is first created. */


    WebView wv;

    JavaScriptInterface JSInterface;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wv = (WebView)findViewById(R.id.webView1);

        wv.getSettings().setJavaScriptEnabled(true);
        // register class containing methods to be exposed to JavaScript

        JSInterface = new JavaScriptInterface(this);
        wv.addJavascriptInterface(JSInterface, "JSInterface"); 

        wv.loadUrl("file:///android_asset/myPage.html");

    }


    public class JavaScriptInterface {
        Context mContext;

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

        public void changeActivity()
        {
            Intent i = new Intent(JavascriptInterfaceActivity.this, nextActivity.class);
            startActivity(i);
            finish();
        }
    }
}

这是html页面:

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
JSInterface.changeActivity();
}
</script>
</head>

<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>

希望这可以帮助。

于 2012-05-30T10:13:08.960 回答
0

是的 - 这是可能的。看起来Java反射在这里起作用。

于 2012-06-07T19:51:37.120 回答