【发布时间】:2017-06-24 17:01:28
【问题描述】:
在OOP 中,我可以使用对象来调用它的方法。所以我想在android中使用相同的概念来做到这一点。但是,它不起作用。我用context调用了函数updateLvl(int),却说方法无法解析。我想知道如何使用context调用方法updateLvl?
public class MainActivity extends Activity {
private WebView webview;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPref = this.getPreferences(0);
editor = sharedPref.edit();
webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebViewJavaScriptInterface2(this), "app");
public void updateLvl(int newLvl){
sharedPref = this.getPreferences(0);
editor = sharedPref.edit();
int be4Level = sharedPref.getInt("currLevel", 1);
if (newLvl >= be4Level){
editor.putInt("currLevel", newLvl);
editor.commit();
}
}
}
class WebViewJavaScriptInterface2{
private Context context;
/*
* Need a reference to the context in order to sent a post message
*/
public WebViewJavaScriptInterface2(Context context){
this.context = context;
}
@JavascriptInterface
public void openLvl(int lvl){
context.updateLvl(lvl);
}
}
【问题讨论】: