WebView从另一个类加载片段中的url

时间:2015-06-24 12:35:02

标签: android android-fragments webview android-jsinterface

我想从其他类调用在Fragment Class中加载URL的方法,但是我为Web视图获取了null值。以下是我的代码。

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的null实例。

      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);
                 }
             });
       }
  }           

1 个答案:

答案 0 :(得分:1)

new WebViewFragment()使您的网页视图无效。相反,您可以创建静态方法loadURL,如:

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

并称之为 -

WebViewFragment.loadURL(Configuration.MOBILE_SITE_URL);