How do i handle closing WebView that opened in Activity Android? - android

Hello i have a weird thing here, i have a list of items and i want when i click on any item, it will open an WebView which looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:theme="#android:style/Theme.Dialog">
<WebView android:id="#+id/BrowserView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
here is the code i invoke the WebView
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
setContentView(R.layout.external_view);
// load url or html
RssItem listItem = (RssItem) listView.getItemAtPosition(position);
webView = (WebView) findViewById(R.id.BrowserView);
// set browser settings
webView.setWebViewClient(new ExternalWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
webView.setInitialScale(1);
try {
webView.loadUrl(listItem.getExternalUrl());
} catch (Exception ex) {
Log.d("WEBVIEW", ex.getMessage());
}
}
});
Here is the "ExternalWebViewClient" class
public class ExternalWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
view.clearHistory();
}
}
Now the question:
How do i close it and stay in the same activity after i press the "back" button,
here is my back button handling code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack() == true) {
webView.goBack();
} else {
//what should i do here?????????????????
return true;
}
}
}
return false;
}

Basically, you should not need to handle Back button yourself. If you are in the WebView and press Back - you should be taken to your last activity by default.

Related

How to make function back button in actionbar like back button in devices android

I have one activity in which there is a webview. when the webview goes to a few pages and I click the back button on the device runs fine, but if I click the back button in the actionbar then return it wrong.
can I make function back button in action bar like back button in the device?
this is my code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tes_backbutton);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
view = (WebView)findViewById(R.id.wv_tes);
progressBar = (ProgressBar)findViewById(R.id.prgbarhome);
view.setWebViewClient(new WebViewClient());
view.loadUrl(URL);
view.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//Required functionality here
return super.onJsAlert(view, url, message, result);
}
});
view.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//Show loader on url load
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(tes_backbutton.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try {
progressDialog.dismiss();
progressDialog = null;
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Intent myIntent = new Intent(tes_backbutton.this, main_noconnect.class);
tes_backbutton.this.startActivity(myIntent);
}
});
view.canGoBack();
view.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& view.canGoBack()) {
view.goBack();
return true;
}
return false;
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
You need to override onOptionsItemSelected method if you want to take any action after back arrow is clicked from action bar like below
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed(); //finishes the activity
return true;
}
return super.onOptionsItemSelected(menuItem);
}
The 'back' button in the action bar should act differently than the device's back button. You don't want them both to do the same thing. The button in the action bar should serve as an 'up' button rather than a 'back' button. Please read more about Providing Up Navigation.
I hope this helps you.
you can use onBackPressed(); method
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
if(mWebView.canGoBack() == true){
mWebView.goBack();
}else{
onBackPressed(); //finishes the activity
}
return true;
}
return super.onOptionsItemSelected(menuItem);
}
you can use webview.cangoback() method for navigating between different web pages in webview
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
if(view.cangoback()){
view.goback();
}
else{
finish();
}
break;
}
return super.onOptionsItemSelected(menuItem);
}

Progress bar doesn't show up while webview is loading

I have written sample webview code by looking at examples found from internet. I want to show progressbar till webview loads a page in my fragment.
My activity contains toolbar, frame that shows fragments and navigation drawer. When i select an entry from navigation drawer, new fragment is shown which contains progress bar and webview and the fragment simply tries to load the page below is the code for fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_full_page, container, false);
//int view_num = getArguments().getInt(ARG_SECTION_NUMBER);
progressBar = (ProgressBar)rootView.findViewById(R.id.webviewProgress);
progressBar.setVisibility(View.VISIBLE);
webView = (WebView) rootView.findViewById(R.id.webView1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
//webView.getSettings().setSupportZoom(true);
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String urlString = getArguments().getString("URLSTRING");
final Boolean clickable = getArguments().getBoolean("CLICKABLE");
Boolean networkAvailable = Utils.isNetworkAvailable(super.getActivity().getApplicationContext());
if(networkAvailable == true) {
webView.loadUrl(urlString);
} else {
webView.loadUrl(Utils.DEFAULT_URL_PAGE);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//progressBar.setVisibility(View.VISIBLE);
if (clickable) {
view.loadUrl(url);
return false;
} else {
return true;
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
});
webView.setOnKeyListener(new View.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;
}
});
return rootView;
}
Below is fragment_full_page.xml
<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=".FragmentFullPage" >
<ProgressBar
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center|top"
android:id="#+id/webviewProgress"
/>
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
web page is taking time to load (tried with wifi and 3g) but progress bar is not showing any time.
To test if progressbar actually shows in the middle of the fragment_full_page, I removed webview code and just kept progress bar then it is showing.
made something wrong with the code that is not showing progress bar while webview is loading which i am unable to figure out.

Clicking Android phone's "go back" button didn't return to the parent view from a webview

I developed an android app which has a list view as its main gui, when the user click the item in the list, a webview will show basing on the content of the item.
It works fine, however when I clicked the back button in the android phone (or simulator), a blank white screen is shown, and the list view appears only after I click the back button again.
Can anyone help explain and help solve the problem?
Here is my WebviewActivity :
public class WebViewActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.active_item_detail);
if (savedInstanceState == null) {
WebViewFragment wvf = new WebViewFragment();
Intent i = this.getIntent();
wvf.init(i.getExtras());
getFragmentManager().beginTransaction().add(R.id.webview, wvf).commit();
}
}
}
and WebviewFragment:
public class WebViewFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.active_item_detail, container, false);
WebView wv = (WebView) v.findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
//data is the content
if(data!=null) {
wv.loadData(data, "text/html", "UTF-8");
}
return v;
}
}
The layout file is like:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<WebView android:id="#+id/webview"
android:layout_height="match_parent"
android:layout_width="wrap_content"
tools:context="com.mycompany.myapp.WebViewFragment" />
</LinearLayout>
private void emulateShiftHeld(){
try
{
KeyEvent shiftPressEvent = new KeyEvent(0, 0,
KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
System.out.println(“shift press:::”+shiftPressEvent.dispatch(view));
}
catch (Exception e){
Log.e(“dd”, “Exception in emulateShiftHeld()”, e);
}
refer to this link https://harshdevchandel.wordpress.com/2013/05/13/android-webview-selection/
check if back is pressed finish this activity
How to handle back button in activity
If a part of your application is contained in a WebView, it may be appropriate for Back to traverse browser history.
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
}
// Otherwise defer to system default behavior.
super.onBackPressed();
}
It is documented in the official docs here
http://developer.android.com/training/implementing-navigation/temporal.html#back-webviews
Try this way:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (wv.canGoBack()) {
wv.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Also, you try with:
#Override
public void onBackPressed() {
Fragment webviewFragment = getSupportFragmentManager().findFragmentByTag("webview");
if (webview instanceof WebViewFragment) {
boolean goback = ((WebViewFragment)webview).canGoBack();
if (!goback)
super.onBackPressed();
}
}
Thanks to all. Unfortunately I couldn't make it after trying all suggestions above. I resolved the problem by creating an intent inside the onBackPressed() hook, and start the initial activity.

Hamburger button in WebView of Android studio does not work

I have a problem in clicking on hamburger button, which was contained in website, website is also called by WebView, like webView.loadUrl(query)
but hamburger button contained in website does not work at all.
Thank you for your help and have a nice day.
as well as that, I also set
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
if(webView.canGoBack()){
webView.goBack();
return false;
}
}
return super.onKeyDown(keyCode, event);
}
private class HybridWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(view != null) {
view.loadUrl(url);
}
return true;
}
}

Android Back Button With Webview

I am having an issue with the back button in my android app. I am trying to have it go back through the previous pages and if unable then to exit. I pick through the code on the developer website and nothing is working. I would appreciate any help.
Below is my activity page:
WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView)findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new myWebView());
webView.loadUrl("http://google.com");
webView.setInitialScale(1);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.diabetes_meal_planner, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.action_settings:
//exits app
finish();
break;
default:
break;
}
return true;
}
private class myWebView extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if(url.startsWith("mailto:"))
{
String[] email = url.split(":");
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email[1]});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Send_Us_Your_Email");
Log.v("NOTICE", "Sending Email to" + email[1] + "with subject" + "Send Us Your Feedback");
startActivity(emailIntent);
}
view.loadUrl(url);
return true;
}
}
Dont do this onKeyDown. Override Activity.onBackPressed to do this..
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView!=null && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
Try this at the end, works in my webview app

Categories

Resources