安卓开发中实现替换webview加载网页失败时的页面和失败后点击后重新加载

京东好物推荐

项目需要在此记录!

Activity中的代码:

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private View mErrorView;
    private RelativeLayout loading_over;
    private String url = "http://www.baidu.com/ ";
    private RelativeLayout webParentView;
    private boolean isSuccess = false;
    private boolean isError = false;
    private LinearLayout ll_control_error;
    private RelativeLayout error;
    private String mobile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webView);
        loading_over = (RelativeLayout) findViewById(R.id.loading_over);
        ll_control_error = (LinearLayout) findViewById(R.id.ll_control_error);
        RelativeLayout error = (RelativeLayout) ll_control_error.findViewById(R.id.online_error_btn_retry);
        error.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_control_error.setVisibility(View.GONE);
                loading_over.setVisibility(View.VISIBLE);
                webView.reload();
            }
        });
        setUpView();

    }

    /**
     * 设置webview参数
     */
    private void setUpView() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//设置支持js
        settings.setDomStorageEnabled(true); //加此行即可出来地图
        webView.loadUrl(url);
        // 此方法可以处理webview 在加载时和加载完成时一些操作
        webView.setWebViewClient(webClient);  //设置Web视图
    }

    /***
     * 设置Web视图的方法
     */
    WebViewClient webClient = new WebViewClient() {//处理网页加载失败时

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            isError = true;
            isSuccess = false;
            //6.0以上执行
            webView.setVisibility(View.GONE);
            ll_control_error.setVisibility(View.VISIBLE);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            isError = true;
            isSuccess = false;
            //6.0以下执行
            webView.setVisibility(View.GONE);
            ll_control_error.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!isError) {
                isSuccess = true;
                //回调成功后的相关操作
                loading_over.setVisibility(View.GONE);
                ll_control_error.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
            } else {
                isError = false;
                loading_over.setVisibility(View.GONE);
                ll_control_error.setVisibility(View.VISIBLE);
            }

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("tel")) {
                mobile = url.substring(url.lastIndexOf("/") + 1);
                //检测权限
                checkPerm();
                //这个超连接,java已经处理了,webview不要处理了
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    };

    /**
     * 检测电话权限
     */
    private void checkPerm() {
        MPermissions.requestPermissions(MainActivity.this, 6, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @PermissionGrant(6)
    public void requestSdcardSuccess() {
        Uri uri = Uri.parse("tel:" + mobile);
        Intent intent = new Intent(Intent.ACTION_CALL, uri);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        startActivity(intent);
    }

    @PermissionDenied(6)
    public void requestSdcardFailed()
    {

    }
    /**
     * 重置返回键
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK&&webView.canGoBack()){
            webView.goBack();
            return true;
        }
        return false;
    }

}

activity_main里的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ddd"
   >
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
    <include layout="@layout/activity_url_error"/>
    <RelativeLayout
        android:id="@+id/loading_over"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#E6E6E6"
        android:gravity="center" >

        <!--<ImageView-->
            <!--android:layout_width="100dp"-->
            <!--android:layout_height="100dp"-->
            <!--android:layout_above="@+id/loading"-->
            <!--android:layout_centerInParent="true"-->
            <!--android:layout_marginTop="3dip"-->
            <!--android:padding="10dip"-->
            <!--android:src="@drawable/ic_launcher" />-->

        <com.zk.projecthelp.LoadingImageView
            android:id="@+id/loading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
           />

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/loading"
            android:layout_centerInParent="true"
            android:layout_marginTop="5dp"
            android:text="正在获取数据..."
            android:textColor="#737373" />
    </RelativeLayout>

</RelativeLayout>

activity_url_error里的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_control_error"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/online_error_btn_retry"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"
        android:background="#ddd"
        android:gravity="center" >

        <ImageView
            android:id="@+id/img_error"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/loading"
            android:layout_centerInParent="true"
            android:layout_marginTop="3dip"
            android:padding="10dip"
            android:src="@mipmap/kong" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/img_error"
            android:layout_centerInParent="true"
            android:layout_marginTop="3dip"
            android:gravity="center"
            android:text="好像没网哦!\n检测网络设置后,戳我重试!"
            android:textColor="#737373" />
    </RelativeLayout>

</LinearLayout>

自定义的LoadingImageView:

public class LoadingImageView extends ImageView {
	private AnimationDrawable mAnimationDrawable;


	public LoadingImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setBackgroundResource(R.drawable.loading);
		mAnimationDrawable = (AnimationDrawable) getBackground();
		mAnimationDrawable.start();
	}

	@Override
	protected void onVisibilityChanged(View changedView, int visibility) {

		super.onVisibilityChanged(changedView, visibility);
		if (visibility == View.GONE) {
			mAnimationDrawable.stop();
		}
	}
}

网上的资料基本没实现失败后点击后重新加载!我这个应该是最简单的实现方法之一了!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨Army

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值