2016-07-19 45 views
1

我的應用程序加載了帶有webView的片段,但是當我嘗試按下後退按鈕時。它崩潰說網絡爲空。我不知道爲什麼。請幫忙。我可以在WebViewFragment嘗試調用空對象上的虛擬方法'布爾android.webkit.WebView.canGoBack()'參考

MainActivity

import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentTransaction; 
import android.webkit.WebView; 

public class MainActivity extends FragmentActivity { 

    WebView mWebView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     FragmentManager fragmentManager = getSupportFragmentManager(); 
     FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
     WebViewFragment webViewFragment = new WebViewFragment(); 
     fragmentTransaction.replace(R.id.mainFragment, webViewFragment); 
     fragmentTransaction.commit(); 
    } 

    @Override 
    public void onBackPressed() { 

      if(mWebView.canGoBack()) { 
       mWebView.goBack(); 

      } 
    else 
     { 
      super.onBackPressed(); 
     } 
    } 

} 

WebViewFragment使用訪問像

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.webkit.WebSettings; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 

public class WebViewFragment extends Fragment { 

    private WebView mWebView; 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_main, container, false); 

     mWebView = (WebView) view.findViewById(R.id.webView); 

     WebSettings webSettings = mWebView.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     mWebView.loadUrl("https://www.google.co.uk/"); 
     mWebView.setWebViewClient(new WebViewClient()); 

     return view; 
    } 

} 

回答

0

mWebView在裏面WebViewFragment.java定義,mWebViewMainActivity.java是不同的對象和值爲空。所以mWebView.canGoBack()將得到錯誤,因爲mWebView是一個空對象。

你應該MainActivity.java修改onBackPressed(),例如:

@Override 
public void onBackPressed() { 
    Fragment webview = getSupportFragmentManager().findFragmentByTag("webview"); 

    if ((webview instanceof WebViewFragment) && WebViewFragment.canGoBack()) { 
      WebViewFragment.goBack(); 
    } else { 
     super.onBackPressed(); 
    } 
} 

而且,獨特的識別片段標籤添加到線fragmentTransaction.replace(...)在MainActivity.java,例如在第三個參數「網頁視圖」:

fragmentTransaction.replace(R.id.mainFragment, webViewFragment, "webview"); 

然後,使mWebView靜態內部class WebViewFragment

private static WebView mWebView; 

,並確保你定義了這2種靜態方法裏面class WebViewFragment

public static boolean canGoBack(){ 
    return myWebView.canGoBack(); 
} 

public static void goBack(){ 
    myWebView.goBack(); 
} 
相關問題