1

我想从其他类调用在片段类中加载 URL 的方法,但是我得到了 web 视图的空值。下面是我的代码。

public class WebViewFragment extends Fragment                                                                                                                             
{                                                                                              
     String url;
     Context context;
     public WebView webViewSite;

     public WebViewFragment()                                               
     {
     }
     public void init(String currentURL, Context context1) 
     {
         url = currentURL;
         context = context1;
     }

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup    container,Bundle savedInstanceState)
     {

         View view = inflater.inflate(R.layout.activity_webview_site, container, false);
         webViewSite = (WebView)view.findViewById(R.id.webViewSite);
         webViewSite.getSettings().setJavaScriptEnabled(true);
         webViewSite.addJavascriptInterface(new JsInterface(context),"AndroidJSObject");
         webViewSite.setWebViewClient(new SwAWebClient());
         webViewSite.setWebChromeClient(new SwAWebChromeClient());
         loadURL(Configuration.MOBILE_SITE_URL);
         return view;
    }
    public  void loadURL(String url)
    {
        webViewSite.loadUrl(url, Configuration.appRequestHeaders);
    }

}

从下面的类我调用 loadURL 方法,但为此我得到了 webview 的空实例。

      public class JsInterface                                                                                          
      {                                                                                                                         
           Handler myHandler;
           private Context mContext;  
           public JsInterface(Context c)
           {
               mContext = c;
               myHandler = new Handler();
           }
           @JavascriptInterface
           public void loadFromBaseUrl()
           {
              myHandler.post(new Runnable()
              {
                 @Override
                 public void run()
                 {
                     Toast.makeText(mContext,"Please Wait",Toast.LENGTH_SHORT).show();
                     new      WebViewFragment().loadURL(Configuration.MOBILE_SITE_URL);
                 }
             });
       }
  }           
4

1 回答 1

1

new WebViewFragment()正在使您的 webview 为空。相反,您可以制作静态方法,loadURL例如:

 public static void loadURL(String url)
    {
        webViewSite.loadUrl(url, Configuration.appRequestHeaders);
    }

并称之为 -

WebViewFragment.loadURL(Configuration.MOBILE_SITE_URL);
于 2015-06-24T13:16:22.210 回答