Issue
I want to open a new activity when I tap on a link in my WebView
, but I don't know how to create a method passing an Object
variable to make a dynamic method. That's why I do it this way actually:
public class WebAppInterface {
public Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void toAbout(){
startActivity(new Intent(MainActivity.this, About.class));
}
@JavascriptInterface
public void toTwitch(){
startActivity(new Intent(MainActivity.this, Twitch.class));
}
@JavascriptInterface
public void toNews(){
startActivity(new Intent(MainActivity.this, News.class));
}
(much more methods like these for specific classes) ...
}
HTML/JS:
<div class="entry" onclick="toTwitch();">Twitch</div>
<div class="entry" onclick="toAbout();">About</div>
<script type="text/javascript">
function toTwitch() {
Android.toTwitch();
}
function toAbout(input) {
Android.toAbout();
}
</script>
MainActivity.java onCreate
:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
// Caching
myWebView.getSettings().setDomStorageEnabled(true);
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
myWebView.getSettings().setAppCachePath(appCachePath);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setAppCacheEnabled(true);
}
Isn't there a way to make just one single method instead of dozens (toAbout()
, toTwitch
, toNews()
, etc.) that is more dynamic?
Solution
Android JavaScript interface supports parameter passing.
You can create a generic method which accepts String
, get the respective Class
and use it on startActivity()
. Note that you have to use fully-qualified name of the Activity
, which means including the package name (e.g. com.example.About
).
Inside WebAppInterface
,
@JavascriptInterface
public void openActivity(String activityName) {
String packageName = "com.example";
try {
Class activityClass = Class.forName(packageName + "." + activityName);
mContext.startActivity(new Intent(MainActivity.this, activityClass));
} catch(Exception ex) {
Toast.makeText(mContext, "invalid activity name: " + activityName, Toast.LENGTH_SHORT).show();
}
}
On HTML/JS,
<script type="text/javascript">
function toTwitch() {
Android.openActivity('Twitch');
}
function toAbout() {
Android.openActivity('About');
}
</script>
Answered By - Andrew T.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.