I have an Android application which uses a WebView to render web page. In css I have set to show everything twice as big for high density screens (like Nexus 7 2013). If I open the web page from the browser, Everything shows as it should. But when I run the app, everything is very small.
Is there any way to determine why the application WebView shows content for lower density screens but browser (Chrome) shows as it should!
Device: Nexus 7 2013
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#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{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
I think this article should help explain what you need to do: https://developers.google.com/chrome/mobile/docs/webview/pixelperfect
I suspect that the difference between Chrome and WebView boils down to the WebSettings that are being applied to the WebView.
Related
I want to Create a Context Menu for web view in android. My problem is that I cant get the URL from the clicked link. I write this code for log the clicked link:
webView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
WebView webView1 = (WebView) v;
WebView.HitTestResult hitTestResult = webView1.getHitTestResult();
Log.i("LinkClicked", hitTestResult.getExtra());
return false;
}
});
With this code, when long click on links in websites like stackoverflow, log like this:
https://stackoverflow.com/questions
everything is ok, but when long click on google search results, log like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAJFBMVEVHcEz/AAD/AAD/AAD/AAD/AAD/AAD/AAD/g4P/////KCj/7e0I8rGvAAAAB3RSTlMAT0g5Ggp+EilkVQAAAENJREFUGJVjYCAGsDAzggEzC5jLxo4E2BgYWNlRACsDM5jmggkwMzCBaQ5uqBATTICTk4OAAEILhqEY1mI4DNPphAAASIsES4gsgWgAAAAASUVORK5CYII=
it does not return a link. How I can fix this?
public class MainActivity extends AppCompatActivity {
WebView webView;
String URL1 = "https://stackoverflow.com/questions/60577403/how-to-get-url-from-long-click-links-in-a-webview/60577736?noredirect=1#comment107173847_60577736";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
public void onPageFinished(WebView view, String url) {
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
URL1 = url;
return super.shouldOverrideUrlLoading(view, url);
}
});
webView.loadUrl(URL1);
// Register the context menu for web view
registerForContextMenu(webView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the web view hit test result
final WebView.HitTestResult result = webView.getHitTestResult();
// If user long press on url
if (result.getType() == WebView.HitTestResult.ANCHOR_TYPE ||
result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
// Set the title for context menu
menu.setHeaderTitle("\t\t\t\t\t\t\t\t\t\t ◦ ◉ ⦿ Select ⦿ ◉ ◦ \t");
// Add an item to the menu
menu.add(0, 1, 0, " \t \t➤\t Show URL")
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
String Pressed_url = result.getExtra();
Toast.makeText(MainActivity.this, "URL is:-" + Pressed_url,
Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
}
Download Full Code from github.
Output
I'm building a App in Android Studio that shows a page in a webview, but I can't seem to get the webview to open pages with target='_blank' in the same webview.
Can this be done?
Currently I have this. As it is now nothing happens when I click a link with target='_blank'
If I change my onCreateWindow I the link open in a external browser, but I don't want tha to happen.
I've tried googling it but can't find a solution.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.myWebView);
myWebView.loadUrl("http://test.dk");
myWebView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setSupportMultipleWindows(true);
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg)
{
WebView.HitTestResult result = view.getHitTestResult();
String data = result.getExtra();
//Context context = view.getContext();
//Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(data));
//context.startActivity(browserIntent); // opens in external browser
myWebView.loadUrl(data); //don't work!
return false;
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
// Use When the user clicks a link from a web page in your WebView
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
}
This is worked for me.Try this one
webView = (WebView) findViewById(R.id.career_view);
URL = "http://test.dk/";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(URL); // Specify the URL to load when the application starts
webView.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
setTitle("Loading...");
setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 70)
setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new SSLTolerentWebViewClient());
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setInitialScale(1); // Set the initial zoom scale
webView.getSettings().setBuiltInZoomControls(true); // Initialize zoom controls for your WebView component
webView.getSettings().setUseWideViewPort(true);
create private class
private class SSLTolerentWebViewClient extends WebViewClient {
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(Activities.this);
AlertDialog alertDialog = builder.create();
String message = "SSL Certificate error.";
switch (error.getPrimaryError()) {
case SslError.SSL_UNTRUSTED:
message = "The certificate authority is not trusted.";
break;
case SslError.SSL_EXPIRED:
message = "The certificate has expired.";
break;
case SslError.SSL_IDMISMATCH:
message = "The certificate Hostname mismatch.";
break;
case SslError.SSL_NOTYETVALID:
message = "The certificate is not yet valid.";
break;
}
message += " Do you want to continue anyway?";
alertDialog.setTitle("SSL Certificate Error");
alertDialog.setMessage(message);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Ignore SSL certificate errors
handler.proceed();
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.cancel();
}
});
alertDialog.show();
}
}
I have writing one app with WebView. My problem is the page can't load in real device. When I had run on an emulator, that page can see all images and contents. My code is looked like below.
My Activity
public class MyActivity extends AppCompatActivity {
private WebView myWebView;
private static final String TAG = "TaoBao";
//private ProgressDialog progressDialog;
FloatingActionMenu materialDesignFAM;
FloatingActionButton floatingActionButton1, floatingActionButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
// webview
myWebView = (WebView) findViewById(R.id.activity_webview);
final WebSettings webSettings = myWebView.getSettings();
//webSettings.setSupportMultipleWindows(true);
//webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
webSettings.setJavaScriptEnabled(true);
// set javascript and zoom and some other settings
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webSettings.setAppCacheEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setAllowContentAccess(true);
myWebView.setScrollbarFadingEnabled(false);
// enable all plugins (flash)
webSettings.setPluginState(WebSettings.PluginState.ON);
// Floating Menu
materialDesignFAM = (FloatingActionMenu) findViewById(R.id.material_design_android_floating_action_menu);
floatingActionButton1 = (FloatingActionButton) findViewById(R.id.material_design_floating_action_menu_item1);
floatingActionButton2 = (FloatingActionButton) findViewById(R.id.material_design_floating_action_menu_item2);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
final ACProgressFlower progressDialog = new ACProgressFlower.Builder(this)
.direction(ACProgressConstant.DIRECT_CLOCKWISE)
.themeColor(Color.WHITE)
.text("Loading...")
.fadeColor(Color.DKGRAY).build();
progressDialog.show();
myWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
// if( URLUtil.isNetworkUrl(url) ) {
// return false;
// }
// if (appInstalledOrNot(url)) {
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// startActivity( intent );
//} else {
// do something if app is not installed
// }
// return true;
view.loadUrl(url);
return false;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " + url);
super.onPageFinished(view, url);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(TaoBao.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
myWebView.loadUrl("https://m.intl.taobao.com/");
}
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}enter code here
main_activity.xml
` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/activity_webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>`
`Here is My Screenshot
Test on Real Device Android 4.3
Test on Emulator Android 4.3
On real device can not see any photo and contents from the web. But on emulator can see image and content. How to fix it can see image and content on real device? Please help me.
Best Regards,
STP
i have 3 diferents screens: main(contains one image), dialog(contains another image) and browser(contains a webView) and one activity source, ok, in the activity source I call the dialog on click image in main layout, then the dialog shows another image and I want when click in the dialog image, the app change main layout for browser layout and then the browser load an specific URI and then close the dialog.
My code dont work becouse i dont know how i need use the webView in separate layout, for example, to call in dialog i need use dialog.findViewById(R.id.webView1) or in main only findViewById(R.id.webView1), but this not work now and the app crash...
My code:
ImageView imgMain = (ImageView)findViewById(R.id.imgMain1);
imgMain.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog dialog = new Dialog(mainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Android");
dialog.setCancelable(true);
dialog.show();
//Boton de cerrar del dialog Android
Button closeDialog = (Button)dialog.findViewById(R.id.closeDialogBT);
closeDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
//click en imagen juegos del dialog android
ImageView imgDialog = (ImageView)dialog.findViewById(R.id.imgDialog1);
imgDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final WebView mWebView = (WebView)findViewById(R.id.webView1);
mWebView.loadUrl("http://www.example.com");
mWebView.setWebViewClient(new WebViewClient());
setContentView(R.layout.browser);
dialog.cancel();
}
});
}
});
Thank You!!!!
Why do you want to start WebView of one Activity from other activity.
It will be better to start activity containing WebView from your "imgDialog" with the intent.
and send URL string in that intent's extras.
in next step load webview with the URL string fetched from intent.
Try this. Hope this will help you
public class Example extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.translate);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.example.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I am using the progress bar for the web view.I need to stop progress bar before the page load.I press the back button but not working in between loading.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar =new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.show();
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i("TEST", "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i("TEST", "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e("TEST", "Error: " + description);
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
mWebView.loadUrl("http://www.google.com");
}
For back button test I use this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Toast.makeText(getApplicationContext(),"hi", Toast.LENGTH_LONG).show();
return true;
}
return super.onKeyDown(keyCode, event);
}
Hi
Please check this out
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
if(progressBar.isShowing())
progressBar.dismiss();
finish();
}
});
progressBar.setMessage("Loading...");
progressBar.show();
Thanks to every one
If I were you, I would use AsyncTask to load the data of the URL, and show the ProgressDialog in between.
On start, spawn off a different thread which fetches the content of the URL
Start displaying the ProgressDialog
When you have the data of the URL that the thread returned, load it in the webView
Dismiss the ProgressDialog
For running things in different thread, check AsyncTask out.
Use Multithreading to implement progress and visual appearence using UIWorker Thread