I have an app in which I have a WebView
where I display some websites. It works, clicking a link in the webpage goes to the next page in the website inside my a
You can try this for webview in a fragment:
private lateinit var webView: WebView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_name, container, false)
webView = root!!.findViewById(R.id.home_web_view)
var url: String = "http://yoururl.com"
webView.settings.javaScriptEnabled = true
webView.webViewClient = WebViewClient()
webView.loadUrl(url)
webView.canGoBack()
webView.setOnKeyListener{ v, keyCode, event ->
if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
&& webView.canGoBack()){
webView.goBack()
return@setOnKeyListener true
}
false
}
return root
}
Webview in Activity,Below code worked for me , Finish the activity the after load the Url in webview.in onbackpressed it go to the previous activity
webView = (WebView) findViewById(R.id.info_webView);
webView.loadUrl(value);
finish();
here is a code with confirm exit:
@Override
public void onBackPressed()
{
if(webView.canGoBack()){
webView.goBack();
}else{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit!")
.setMessage("Are you sure you want to close?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
The first answer by FoamyGuy is correct but I have some additions; low reputations cannot allow me to do comments. If for some reasons your page fails to load, ensure that you set a flag to take note of the failure and then check it on the onBackPressed override. Otherwise your canGoBack() will be forever executed without heading to the actual back activity if it was there:
//flag with class wide access
public boolean ploadFailFlag = false;
//your error handling override
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
ploadFailFlag = true; //note this change
.....
.....
}
//finally to the answer to this question:
@Override
public void onBackPressed() {
if(checkinWebView.canGoBack()){
//if page load fails, go back for web view will not go back - no page to go to - yet overriding the super
if(ploadFailFlag){
super.onBackPressed();
}else {
checkinWebView.goBack();
}
}else {
Toast.makeText(getBaseContext(), "super:", Toast.LENGTH_LONG).show();
super.onBackPressed();
}
}
Why not use onBackPressed()
?
@Override
public void onBackPressed()
{
// super.onBackPressed(); Do not call me!
// Go to the previous web page.
}