2012-05-30 28 views
0

是否可以使用私有內部類作爲WebView的Javascript接口?使用私有類作爲Javascript接口

public class WebController{ 

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

    private class JSInterface{ 

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

    } 

} 

回答

0

是的 - 這是可能的。看起來像Java反射在這裏工作。

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> 

希望這會有所幫助。

+0

你的課程不是私人的 –