如何在 webview 中对多个 URL 进行 facebook 评论 activity?

How to make facebook comment activity for multiple URLs in webview?

我正在尝试构建 Webview 应用程序,用户可以在其中 post 使用 facebook 评论 activity 在网页上发表评论。如果 URL 在 webview 中不断变化,如何将 URL 变为 FbCommentActivity.java。请注意,Facebook Comment Plugin 已安装在所有网页中。

我尝试在我的 webview 片段中使用 "TAG_LINK",它在按下书签按钮时存储应用程序链接,但仍然无法正常工作。另请注意,如果我使用 mWebViewComments.loadDataWithBaseURL("http://www.example.com") 评论正在加载,因为评论用于定义 http BaseURL 方法的不同页面失败。 例如:我有两个网页 http://example/page1, http://example/page2。如何在有多个网页时进行评论activity。 我也试过 webview.getUrl() 方法 例如:postUrl = webview.getUrl();但是当我点击 comment fab 按钮时,应用程序崩溃了。 请分享您的宝贵意见。我是 android 的新手,请帮助我。

FbCommentsActivity.java

 package seacoders.abhilash.bogguru;


 import android.net.Uri;
 import android.net.http.SslError;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.view.ViewGroup;
 import android.webkit.ConsoleMessage;
 import android.webkit.CookieManager;
 import android.webkit.SslErrorHandler;
 import android.webkit.WebChromeClient;
 import android.webkit.WebSettings;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;
 import android.widget.FrameLayout;
 import android.widget.ProgressBar;
 import android.widget.Toast;
 import seacoders.abhilash.bogguru.HomeFragment;

 public class FbCommentsActivity extends AppCompatActivity {
  private static String TAG = FbCommentsActivity.class.getSimpleName();
  private WebView mWebViewComments;
  private FrameLayout mContainer;
  private ProgressBar progressBar;
  boolean isLoading;
  private WebView mWebviewPop;
  private String postUrl;
  //    public String webUrl = getIntent().getExtras().getString("webUrl");
  // error is coming from here, according the the error log.

  // the default number of comments should be visible
  // on page load.
  private static final int NUMBER_OF_COMMENTS = 8;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_fb_comments);
   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);
   getSupportActionBar().setDisplayHomeAsUpEnabled(true);

   mWebViewComments = (WebView) findViewById(R.id.commentsView);
   mContainer = (FrameLayout) findViewById(R.id.webview_frame);
   progressBar = (ProgressBar) findViewById(R.id.progressBar);
   progressBar.setVisibility(View.VISIBLE);

   postUrl = getIntent().getStringExtra("TAG_LINK");
   // finish the activity in case of empty url
   if (TextUtils.isEmpty(postUrl)) {
    Toast.makeText(getApplicationContext(), "The web url shouldn't be empty", Toast.LENGTH_LONG).show();
    finish();
    return;
   }

   setLoading(true);
   loadComments();
  }

  private void loadComments() {
   mWebViewComments.setWebViewClient(new UriWebViewClient());
   mWebViewComments.setWebChromeClient(new UriChromeClient());
   mWebViewComments.getSettings().setJavaScriptEnabled(true);
   mWebViewComments.getSettings().setAppCacheEnabled(true);
   mWebViewComments.getSettings().setDomStorageEnabled(true);
   mWebViewComments.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
   mWebViewComments.getSettings().setSupportMultipleWindows(true);
   mWebViewComments.getSettings().setSupportZoom(false);
   mWebViewComments.getSettings().setBuiltInZoomControls(false);
   CookieManager.getInstance().setAcceptCookie(true);
   if (Build.VERSION.SDK_INT >= 21) {
    mWebViewComments.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    CookieManager.getInstance().setAcceptThirdPartyCookies(mWebViewComments, true);
   }

   // facebook comment widget including the article url
   String html = "<!doctype html> <html lang=\"en\"> <head></head> <body> " +
    "<div id=\"fb-root\"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = \"//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6\"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> " +
    "<div class=\"fb-comments\" data-href=\"" + postUrl + "\" " +
    "data-numposts=\"" + NUMBER_OF_COMMENTS + "\" data-order-by=\"reverse_time\">" +
    "</div> </body> </html>";

   mWebViewComments.loadDataWithBaseURL(postUrl, html, "text/html", "UTF-8", null);
   mWebViewComments.setMinimumHeight(200);
  }

  private void setLoading(boolean isLoading) {
   this.isLoading = isLoading;

   if (isLoading)
    progressBar.setVisibility(View.VISIBLE);
   else
    progressBar.setVisibility(View.GONE);

   invalidateOptionsMenu();
  }

  private class UriWebViewClient extends WebViewClient {
   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {

    String host = Uri.parse(url).getHost();

    return !host.equals("m.facebook.com");

   }

   @Override
   public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    String host = Uri.parse(url).getHost();
    setLoading(false);
    if (url.contains("/plugins/close_popup.php?reload")) {
     final Handler handler = new Handler();
     handler.postDelayed(new Runnable() {
      @Override
      public void run() {
       //Do something after 100ms
       mContainer.removeView(mWebviewPop);
       loadComments();
      }
     }, 600);
    }
   }

   @Override
   public void onReceivedSslError(WebView view, SslErrorHandler handler,
    SslError error) {
    setLoading(false);
   }
  }

  class UriChromeClient extends WebChromeClient {

   @Override
   public boolean onCreateWindow(WebView view, boolean isDialog,
    boolean isUserGesture, Message resultMsg) {
    mWebviewPop = new WebView(getApplicationContext());
    mWebviewPop.setVerticalScrollBarEnabled(false);
    mWebviewPop.setHorizontalScrollBarEnabled(false);
    mWebviewPop.setWebViewClient(new UriWebViewClient());
    mWebviewPop.setWebChromeClient(this);
    mWebviewPop.getSettings().setJavaScriptEnabled(true);
    mWebviewPop.getSettings().setDomStorageEnabled(true);
    mWebviewPop.getSettings().setSupportZoom(false);
    mWebviewPop.getSettings().setBuiltInZoomControls(false);
    mWebviewPop.getSettings().setSupportMultipleWindows(true);
    mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
     ViewGroup.LayoutParams.MATCH_PARENT));
    mContainer.addView(mWebviewPop);
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(mWebviewPop);
    resultMsg.sendToTarget();

    return true;
   }

   @Override
   public boolean onConsoleMessage(ConsoleMessage cm) {
    Log.i(TAG, "onConsoleMessage: " + cm.message());
    return true;
   }

   @Override
   public void onCloseWindow(WebView window) {}
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
   if (!isLoading) {
    getMenuInflater().inflate(R.menu.fb_comments, menu);
   }

   return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
   if (item.getItemId() == android.R.id.home) {
    onBackPressed();
    return true;
   }

   if (item.getItemId() == R.id.action_refresh) {
    mWebViewComments.reload();
   }

   return super.onOptionsItemSelected(item);
  }
 }

HomeFragment.java

package seacoders.abhilash.bogguru;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.net.URI;
import java.util.ArrayList;
import seacoders.abhilash.bogguru.FavFragment;
import static seacoders.abhilash.bogguru.FavFragment.TAG_LINK;

public class HomeFragment extends Fragment {
 static WebView wv, cv = null;
 TextView txt;
 ProgressBar pbar;
 FloatingActionButton cmt, fav;
 Context mcontext;



 public static final String PREFERENCES = "PREFERENCES_NAME";
 String WEB_LINKS = "links";
 String WEB_TITLE = "title";
 //String PageURL = getActivity().getIntent().getStringExtra("url");
 public String current_page_url;
 public static final String TITLE = "Home";


 public static HomeFragment newInstance() {

  return new HomeFragment();
 }

 @Nullable
 @Override
 public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
  //return inflater.inflate(R.layout.fragment_home, container, false);
  setHasOptionsMenu(true);
  final View v = inflater.inflate(R.layout.fragment_home, container, false);
  wv = (WebView) v.findViewById(R.id.webview);
  wv.loadUrl("http://bogguru.we.bs/bogguru-android-mobile-application/webapp/index.html");
  current_page_url = "http://bogguru.we.bs/bogguru-android-mobile-application/webapp/";
  SharedPreferences sharedPreferences = getActivity().getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
  String links = sharedPreferences.getString(WEB_LINKS, null);
  if (links != null) {
   Gson gson = new Gson();
   ArrayList < String > linkList = gson.fromJson(links, new TypeToken < ArrayList < String >> () {}.getType());
  }

  if (getActivity().getIntent().getExtras() != null) {
   TAG_LINK = getActivity().getIntent().getStringExtra("url");
  }
  //facebook comment
  cmt = (FloatingActionButton) v.findViewById(R.id.fabcmt);
  cmt.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    // launching facebook comments activity
    Intent intent = new Intent(getActivity(), FbCommentsActivity.class);

    //fb comment passing the article url
    intent.putExtra("TAG_LINK", "http://www.bogguru.we.bs/");
    startActivity(intent);
   }
  });
  // end of fb comment
 }
}

activity_fb_comment.xml

<
android.support.design.widget.CoordinatorLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: fitsSystemWindows = "true"
tools: context = ".FbCommentsActivity" >

 <
 android.support.design.widget.AppBarLayout
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: theme = "@style/AppTheme.AppBarOverlay" >

 <
 android.support.v7.widget.Toolbar
android: id = "@+id/toolbar"
android: layout_width = "match_parent"
android: layout_height = "?attr/actionBarSize"
android: background = "?attr/colorPrimary"
app: popupTheme = "@style/AppTheme.PopupOverlay" / >

 <
 /android.support.design.widget.AppBarLayout>

 <
 LinearLayout
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: orientation = "vertical"
app: layout_behavior = "@string/appbar_scrolling_view_behavior" >

 <
 FrameLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android: id = "@+id/webview_frame"
android: layout_width = "match_parent"
android: layout_height = "match_parent" >

 <
 WebView
android: id = "@+id/commentsView"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: layout_gravity = "center_horizontal" / >

 <
 ProgressBar
android: id = "@+id/progressBar"
android: layout_width = "30dp"
android: layout_height = "30dp"
android: layout_alignParentBottom = "true"
android: layout_centerHorizontal = "true"
android: layout_gravity = "center"
android: layout_marginBottom = "10dp"
android: indeterminateTint = "@color/colorPrimary"
android: indeterminateTintMode = "src_atop" / >

 <
 /FrameLayout> <
 /LinearLayout>

 <
 /android.support.design.widget.CoordinatorLayout>

宾果!!!最后这对我有用。我在 FbCommentsActivity.java

中添加了以下行
 WebView wv = (WebView) findViewById(R.id.webview);// my HomeFragment WEBVIEW
    postUrl = HomeFragment.wv.getUrl(); //get Url from Homefragment webview