如果设备处于离线状态,则会在片段webview中显示警告

时间:2017-10-18 05:00:55

标签: android android-fragments webview toast android-internet

如果设备离线,我想在片段webview 中显示提醒弹出窗口,而不是显示默认消息('网页.....&#39 )。我是Android应用程序开发领域的新手。我已经添加了进度条,但我无法知道在哪里以及包含toast代码以提醒消息的内容。这是我的tabinfo.java

tabinfo.java

public class tabinfo extends Fragment{

    public WebView mwebView;
    ProgressBar bar;

    public tabinfo(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.tabinfo, null);
        bar = (ProgressBar) rootView.findViewById(R.id.progressBar2);
        // initialize bar

        mwebView = (WebView) rootView.findViewById(R.id.webview);
        mwebView.loadUrl("https://mbasic.facebook.com");
        mwebView.getSettings().setJavaScriptEnabled(true);
        mwebView.setWebViewClient(new MyWebViewClient());
        return rootView;
    }

    private class MyWebViewClient extends WebViewClient {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
            bar.setVisibility(View.VISIBLE);
            // ^^^ use it as it is

            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            bar.setVisibility(View.GONE);
            // ^^^ use it as it is
            super.onPageFinished(view, url);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在MyWebViewClient类中覆盖onReceivedError方法

@Override
public void onReceivedError(WebView view, int errorCode, String description, 
String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);

view.loadUrl("about:blank");
ConnectivityManager cm = (ConnectivityManager) 
getSystemService(Context.CONNECTIVITY_SERVICE);

if(cm.getActiveNetworkInfo() != null){
 Toast toast = Toast.makeText(context, " Internet Connected", Toast.LENGTH_LONG).show();
}
else
Toast toast = Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_LONG).show;
}
清单中的

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在Fragment中获取上下文

Context context;
@Override
public void onAttach(Context context) {
super.onAttach(context);
 this.context = context;
}