2017-05-26 42 views
0

我正在创建一个移动应用程序,并在我的MainActivity类的android studio中,我试图调用一个内部片段类中的方法。在这个片段类我有另一个类称为WebViewInterface:如何访问java(android)中的内部类?

public class tab2_upgrade extends Fragment { 

    Context context; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.tab2_upgrade, container, false); 
     WebView webView = (WebView) view.findViewById(R.id.webView); 
     webView.loadUrl("file:///android_asset/tab2.html"); 
     webView.getSettings().setJavaScriptEnabled(true); 
     webView.addJavascriptInterface(new WebViewInterface(getActivity()), "Android"); 

     return view; 
    } 

    public class WebViewInterface { 

     WebViewInterface(Context myWebViewFragment) { 
      context = myWebViewFragment; 
     } 

     @JavascriptInterface 
     public void showToast(String message) { 
      Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 
     } 

但是当我试图访问这个内部类从我的MainActivity内它来调用一个方法,我得到,如果它不承认它是一个错误(但可以找到它):

@Override 
public void onProductPurchased(String productId, TransactionDetails details) { 
    tab2_upgrade tab2 = new tab2_upgrade(); 
    tab2.WebViewInterface tab2WebView = new tab2.WebViewInterface(); 
} 

@Override 
public void onProductPurchased(String productId, TransactionDetails details) { 
    tab2_upgrade tab2 = new tab2_upgrade(); 
    tab2.WebViewInterface tab2WebView = tab2.new WebViewInterface(); 
} 

可能有人请告诉我为什么我收到此错误,以及如何解决这个问题,这样我可以访问WebViewInterfaceç在我的片段类?请参阅附件中的图片以查看红色错误。由于

enter image description here

enter image description here

enter image description here

+0

您没有无参数构造函数。 – Adrian

回答

0

错误是告诉你的是,WebViewInterface构造函数接受一个Context的说法,但是你要调用它不带任何参数。

顺便说一下,tab2_upgradeWebViewInterface是类非常混乱的名称。请参阅官方指南naming conventions

+0

我如何获得适当的上下文传递给它?我的MainActivity类myWebViewFragment上下文? – Tanya

+0

@Tanya为什么要在所有环境中传递,而不是在需要上下文时调用'Fragment'调用getActivity()'?我会说你需要重新思考一切,但我正在努力专注于你的具体问题。 –

+0

我将它添加到我的JavaScript界面​​中: webView.addJavascriptInterface(new WebViewInterface(getActivity()),“Android”); – Tanya