【问题标题】:Android - How to open a fragment from current fragment activity on clicking a URL in WebView?Android - 如何在单击 WebView 中的 URL 时从当前片段活动中打开片段?
【发布时间】:2018-10-22 18:47:32
【问题描述】:

我有一个带有 WebView 的片段活动,我希望在单击特定 url 时在其中打开或重定向到不同的片段。

注意:如果选择了不同于所需的 URL,它应该在同一个当前片段中打开。

【问题讨论】:

    标签: android android-layout android-fragments android-intent


    【解决方案1】:

    您应该覆盖 url 加载。 使用如下内容:

    webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("your_url")) { //you can also use indexOf, equales etc. 
            // do what's needed
            return true;
        }
        return false;
    }
    

    });

    【讨论】:

      【解决方案2】:

      在你为 webview 提供代码的 on-create 中添加这个(最好在 oncreate 方法的末尾添加)

      webView.setWebViewClient(new MyWebViewClient());
      

      然后在 oncreate 之外进行如下函数调用

      private class MyWebViewClient extends WebViewClient {
      
         @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {
      
              if (url.equals("your url here")) {
                  Fragment newFragment = YourNewFrag();
                  // consider using Java coding conventions (upper first char class names!!!)
                  FragmentTransaction transaction = getFragmentManager().beginTransaction();
      
                  // Replace whatever is in the fragment_container(usually a frame layout) view with this fragment,
                  // and add the transaction to the back stack
                  transaction.replace(R.id.fragment_container, newFragment);
                  transaction.addToBackStack(null);
      
                  // Commit the transaction
                  transaction.commit();
                  return true;
              }
              return false;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多