2017-05-26 38 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