UPDATE: Solved! Problem was related to my Viewpager not WebView.
I'm trying to add a "Go Back" function to my WebView
which is inside a Fragment
. But I can't figure out how to:
public final class TestFragment extends Fragment {
static WebView mWeb;
private View mContentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mContentView = inflater.inflate(R.layout.webview, null);
mWeb = (WebView)mContentView.findViewById(R.id.webview);
WebSettings settings = mWeb.getSettings();
settings.setJavaScriptEnabled(true);
settings.setSupportZoom(false);
mWeb.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWeb.getSettings().setBuiltInZoomControls(false);
mWeb.loadUrl("myurl...");
mWeb.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
mWeb.goBack();
return true;
}
return false;
}
});
}
}
I also tried something like:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
mWeb.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
Another solution but same problem:
@Override
public void onBackPressed()
{
if(webView.canGoBack())
webView.goBack();
else
super.onBackPressed();
}
Any ideas how to get this working?
my solution was in fragment I added to public methods
then from activity I call
note The mwebview is static
In
WebViewActivity.java
, I added 1 method:In
WebViewFragment.java
, I added 2 methods:Actually you can not do directly inside the fragment. The
onBackPressed
can be overridden in theFragmentActivity
. What you can do is:onBackPressed
inside the activity.onBackPressed
is called, check if the instance of the current fragment is the instance showing thewebview
.fragment
if thewebview
can go back.super
or whatever you needEdit:
you can do this by :
in the
Activity
put :in the web fragment after
ActivityCreated()
put:((Your_Activity) getActivity()).setWebView(webView);
Don't forget to set
webView
from theonCreateView()
like these:You can check this code :
I've created a simple interface:
in the Activity:
in the Fragment: