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!
Related
I am using fragment with WebView. Webview opens up correctly. My intention is as follows: Visitor clicks on any of the links within WebView inside the Fragment. Clicked link opens up in new WebView within new Activity. Tricky part - all links are from the same web site, there are no external links. Tricky for me, at least. Many thanks for your help in advance! :)
Here is my WebView code from Fragment:
public class HomeFragment extends Fragment {
#SuppressLint("SetJavaScriptEnabled")
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_naslovna, container, false);
WebView webView = view.findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://mywebpage.com/");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
return view;
}
}
Please try this:
WebViewClient webClient = new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if( url.equals("http://test.com") ){
// do whatever you want e.g. open up activity with web view and pass the url
}
return true;
}
}
It took 6 more hours u puzzle work, but this is how it got fixed at the end.
public class HomeFragment extends Fragment {
WebView webView;
SwipeRefreshLayout swipeToRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_naslovna, container, false);
webView = view.findViewById(R.id.webView1);
final String pageUrl = "https://mywebpage.com/";
swipeToRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swiperefresh);
swipeToRefreshLayout.setOnRefreshListener(new RtvTkSwipeToRefreshListener(webView, swipeToRefreshLayout));
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != pageUrl) {
startNewActivity(url);
}
return true;
}
});
webView.loadUrl(pageUrl);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
return view;
}
private void startNewActivity(String url) {
Intent myIntent = new Intent(getActivity(), NewActivity.class);
myIntent.putExtra("url", url);
getActivity().startActivity(myIntent);
}
}
Hi I'm trying to call a webview fragment when an item of recyclerview is clicked, I made a fragment with it's layout for the webview, and I have an adapter to call the fragment but it shuts down the APP:
public class WebViewFragment extends Fragment {
public WebView mWebView;
public WebViewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mWebView = (WebView) mWebView.findViewById(R.id.webview);
mWebView.loadUrl("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 inflater.inflate(R.layout.fragment_web_view, container, false);
}
}
And the adapter:
#Override
public void onClick(View view) {
int position = (int) view.getTag();
News news =newsItems.get(position);
Uri uri = Uri.parse(news.getLink());
Intent intent = new Intent(mACtivity, WebViewFragment.class);
mACtivity.startActivity(intent);
}
Layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="tech.amro.amro.WebViewFragment">
<!-- TODO: Update blank fragment layout -->
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webview"/>
</FrameLayout>
I know I'm not sending the url to the webview yet but I'm just testing to load the view first then sending the url. but when the item is clicked it shuts down the APP. and gives this error:
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tech.amro.amro, PID: 18958
android.content.ActivityNotFoundException: Unable to find explicit activity class {tech.amro.amro/tech.amro.amro.WebViewFragment}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1932)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1615)
at android.app.Activity.startActivityForResult(Activity.java:4472)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:4430)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
at android.app.Activity.startActivity(Activity.java:4791)
at android.app.Activity.startActivity(Activity.java:4759)
at tech.amro.amro.adapters.NewsAdapter.onClick(NewsAdapter.java:73)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Application terminated.
If you don't have a specific reason to use a WebView you could just use an Intent to start a web browser as follows.
#Override
public void onClick(View view) {
int position = (int) view.getTag();
News news = newsItems.get(position);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(news.getLink()));
startActivity(i);
}
Note you probably would need to check if the device can handle the URI - some people might not have a browser installed which will result in an ActivityNotFoundException.
If you do need to use the WebView you have a couple of issues:
Fragments can't be started the same way you start an activity, to display a fragment you need to use the FragmentManager in order to add it into your Activity.
Regarding your Fragment, the onCreateView code won't work. You need to inflate the xml first that contains your webview and then find the webview from that layout.
At the moment you're trying to find the webView from the webView which will result in a NullPointerException.
You should also prefer onViewCreated to find and load the WebView url.
Your fragment should probably look something like the following
public class WebViewFragment extends Fragment {
private static final String NEWS_LINK_KEY = "NEWS_LINK";
private String newsLink;
public static WebViewFragment newInstance(String uri) {
Bundle args = new Bundle();
args.putString(NEWS_LINK_KEY, uri);
WebViewFragment webViewFragment = new WebViewFragment();
webViewFragment.setArguments(args);
return webViewFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newsLink = this.getArguments().getString(NEWS_LINK_KEY);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.web_view, container, false)
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
WebView webView = (WebView) view.findViewById(R.id.webview);
// Enable Javascript
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(newsLink);
}
}
This could be started from the onClick method as follows:
#Override
public void onClick(View view) {
int position = (int) view.getTag();
News news = newsItems.get(position);
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, WebViewFragment.newInstance(news.getLink()))
.commit();
}
The DialogFragment has a webview.
Everytime show the DialogFragment,the webview will take some time to load the webview, and before the webpage finished loading, the webview will show the background color. This will affect the user experience. So i want to use some method to preload webview. But really get me there is that m_webviewDialog.show will start two function onCreateDialog and onCreateView. So is there anyway make the webview preload and then add in the onCreateView fucnion?
main activity show code:
public void showWebviewDialog()
{
FragmentManager fragmentManager=getFragmentManager();
if(m_webviewDialog!=null&&m_webviewDialog.isAdded())
{
m_webviewDialog.getDialog().show();
}
else {
m_webviewDialog=mcWebViewDialog.newInstance();
m_webviewDialog.set_loadurl("file:///android_asset/input.html");
m_webviewDialog.show(fragmentManager,"mcWebDialog");
}
}
DialogFragment code:
WebView m_webView;//WebView component
String m_loadurl;
static mcWebViewDialog newInstance()
{
mcWebViewDialog f=new mcWebViewDialog();
return f;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// other code
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
m_webView = new WebView(getActivity());
//other code
return m_webview;
}
I had an issue, that webview (in DialogFragment) is minimized to zero height althogh it has data. so I used relaod. you must be sure that WebView has data, or you will go to non-ending loop becouse reload leads to onPageFinished and vise versa.
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (view.getContentHeight() == 0){
view.reload();
}
}
...
}
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.
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");