I created a WebView using Fragment; here is my code:
public class MyWebView extends Fragment {
private WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
String url = args.getString("url");
webView = (WebView) getView().findViewById(R.id.webView);
webView.setWebViewClient(new MyBrowser());
WebSettings webSettings = webView.getSettings();
webSettings.setSaveFormData(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadUrl(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.web_view, container, false);
view.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
return true;
}
}
return false;
}
});
return view;
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
I tried to override onBackPressed() but it seems not to work with Fragment. So I used setOnKeyListener() but it doesn’t work.
Can you tell me why the back button closes the app instead of going back to the previous web page?
The Fragment doesn't receive a callback of the OnBackPressed event. You'll have to make your Activity state aware when your fragment is displayed and communicate back and forth between the activity and the fragment.
You could make your code you're calling in on key a public boolean function for instance and if the fragment is present you interact with it, you continue to return true or false in a similar way which allows you to know on the activity if you should continue with it naturally if there are no more pages to go back.
Related
At my navigationDrawer from menu , by clicking search it opens a specific webview in a fragment . Works fine, but when I press back on that webview - instead of getting the last visited webscreen it comes back to my main fragment. how can i solve this? I'm providing my fragment java file here. please mention any other codes to need (if needed) to solve my problem
public class GoogleFragment extends Fragment {
public WebView mWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(fragment_google, container, false);
mWebView = (WebView) v.findViewById(webview);
mWebView.loadUrl("https://google.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webview performance
mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
return v;
}
}
I think when you press back button from fragment than we need to handle it inside of Activity,
You need to first Override onBackPressed() method in your main activity which having fragment and global assign Webview with public in your google fragment
NOTE : when you are adding or replacing fragment keep adding a TAG, it can be helpful for getting instance of fragment.
#Override
public void onBackPressed() {
Fragment fragment =
getFragmentManager().findFragmentByTag("google_fragment");
if (fragment instanceof GoogleFragment) {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}else{
super.onBackPressed();
}
}
public class GoogleFragment extends Fragment {
public WebView mWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(fragment_google, container, false);
mWebView = (WebView) v.findViewById(webview);
mWebView.loadUrl("https://google.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webview performance
mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnKeyListener( new View.OnKeyListener()
{
#Override
public boolean onKey( View v1, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK ) {
if(mWebView.canGoBack())
{
wView.goBack();
wView.getUrl();
}
return true;
}
return false;
}
} );
return v1;
}
}
Please try this code .it may help you.
public class PrimaryFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.primary_layout, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webView);
WebSettings webSettings = heroespage.getSettings();
webSettings.setJavaScriptEnabled(true);
heroespage.setWebViewClient(new MyBrowser());
heroespage.loadUrl("http://beritagresik.com");
return rootView;}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url ){
view.loadUrl(url);
return true;
}}}
This is sample my application, plis help for resolve this problem
thanks for ur help
If you open a web url in webview and inside is you open another link and so on.
now you want to come back by page , you can use webView.goBack();
Try out this code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (heroespage.canGoBack()) {
heroespage.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
How can I go back one page while in webview? For example: I am on my app in activity and browsing pages in webview, but once I press back button it will exit the app or just goes back in activity instead of the page..
I have done my research and overriding onBackPressed function doesnt work.
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
Whole fragment code:
public class FragmentTwo extends Fragment {
public FragmentTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment2, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
WebView webView = (WebView) getActivity().findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webView.setScrollbarFadingEnabled(false);
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://myapp.com");
}
}
Any suggestions of how to achieve it?
onBackPressed() is method of Activity, not of a Fragment, so this code will never be invoked. If you want to do something on back press, your parent activity must let your fragment know about it - you must implement onBackPressed() in parent activity and in that method you should call fragments' method (or fire event on event bus, or use listeners, callback, whatever).
Also right method name is onCreateView(), not onViewCreated() - this one won't be called either.
Inside of the your OnCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.your_layout, container, false);
webView = (WebView) view.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(expertsUrl);
return view;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Ok! In your MainActivity you will write it:
#Override
public void onBackPressed() {
if(yourname_Fragment.webView!=null){
if (yourname_Fragment.webView.canGoBack()) {
yourname_Fragment.webView.goBack();
}
}
}
yourname_Fragmen.java= This is your nameFragment that content the Webview
webView= The name of your WebView (id)
Now. Inside of your Fragment you have to declare static global variable
public static Webview webView;
NOTE: If you have more than one fragment you have to check if this instance is different of NULL;
And that's it! Good luck!
Very good at all.
I have a fragment is called a drawerlist. Within this fragment I have a webView showing a web page.
I can surf the web, but the problem comes when I want to return to the previous page, and pulse on the back button.
The result I get is that pressing the back button, the application closes. And what I want is to return to the previous page.
Code fragment is as follows:
public class BClasesWebViewFragment extends Fragment {
private WebView webView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
WebSettings webSettings = this.webView.getSettings ();
webSettings . setJavaScriptEnabled ( true );
webSettings . setDomStorageEnabled ( true );
this . webView . setWebViewClient ( new WebViewClient ());
this . webView . setWebChromeClient ( new WebChromeClient ());
webSettings . setLoadWithOverviewMode ( true );
webSettings . setUseWideViewPort ( true );
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl("http://google.com/");
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bclases_webview, container, false);
webView = (WebView)view.findViewById(R.id.webViewBClases);
return view;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.actionbar_menu, menu);
super.onCreateOptionsMenu(menu,inflater);
}
}
Thank you very much everyone.
I learned a lot on this site
Try this
webView.setOnKeyListener(new OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
this will work perfectly.
I created a small Android 4 application with fragments.
In all these fragments I have some webviews and if I click a different fragment I want a different website to load.
I have right now TabOne.java ; TabTwo.java ; TabThree.java and so on.
I was also wondering : Can I make this application without needing a TabOne.java, TabTwo.java and so on; only from MainActivity.java? I mean, to have a single WebView, and when clicking different Tabs, this WebView to load different Url (according to the selected Tab).
If this is not possible, can you tell me what is wrong here (TabOne.java) :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.tabone, container, false);
myWebView = (WebView) view.findViewById(R.id.webview);
myWebView.getSettings().setPluginsEnabled(true);
myWebView.loadUrl("http://m.stirileprotv.ro");
myWebView = new WebView(getActivity());
myWebView.setOnKeyListener(new OnKeyListener(){
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
{
myWebView.goBack();
return true;
}
return false;
}
});
myWebView.setWebViewClient(new WebViewClient() {
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("m.stirileprotv.ro")) {
myWebView.loadUrl(url);
return true;
}
else
{
return false;
}
}
});
return view;
}
This is what i did.
In the fragment, declare the webview reference as static-
public static WebView mWebView;
public WebFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_web, container, false);
mWebView = (WebView) v.findViewById(R.id.webview);
mWebView.loadUrl("https://google.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
return v;
}
public boolean canGoBack() {
return mWebView.canGoBack();
}
public void goBack() {
mWebView.goBack();
}
}
Now, In the parent activity -
#Override
public void onBackPressed() {
WebFragment fragment = new WebFragment();
if (fragment.mWebView.canGoBack()) {
fragment.mWebView.goBack();
} else {
super.onBackPressed();
}
}
What I did was implement it within the activity and then have a public static so:
In the main activity:
public class MainActivity extends FragmentActivity{
public static WebView myWebView;
...
#Override
public void onBackPressed() {
if (getSupportFragmentManager().findFragmentByTag("yourtag") != null) {
if(myWebView.canGoBack())
myWebView.goBack();
else {
super.onBackPressed();
}
}
else
super.onBackPressed();
}
...
}
and to reference it within the fragment:
MainActivity.myWebView = (WebView) getView().findViewById(R.id.webview);
and be sure when you create the fragment you add a tag
transaction.replace(R.id.yourfragid, newfragment, "yourtag");