List of usage examples for android.webkit WebSettings setSupportZoom
public abstract void setSupportZoom(boolean support);
From source file:com.tfc.webviewer.ui.WebViewerActivity.java
@SuppressLint("SetJavaScriptEnabled") private void bindView() { // Toolbar/* w w w . j a v a2 s. com*/ mTvTitle = (TextView) findViewById(R.id.toolbar_tv_title); mTvUrl = (TextView) findViewById(R.id.toolbar_tv_url); mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.a_web_viewer_coordinatorlayout); mProgressBar = (ProgressBar) findViewById(R.id.a_web_viewer_pb); mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.a_web_viewer_srl); mWebView = (WebView) findViewById(R.id.a_web_viewer_wv); mSwipeRefreshLayout.setOnRefreshListener(this); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webSettings.setDisplayZoomControls(false); } webSettings.setBuiltInZoomControls(true); webSettings.setSupportZoom(true); webSettings.setDomStorageEnabled(true); mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.setWebViewClient(new MyWebViewClient()); mWebView.setDownloadListener(this); mWebView.setOnCreateContextMenuListener(this); mBtnMore = (AppCompatImageButton) findViewById(R.id.toolbar_btn_more); //noinspection ConstantConditions findViewById(R.id.toolbar_btn_close).setOnClickListener(this); //noinspection ConstantConditions mBtnMore.setOnClickListener(this); // PopupWindow initPopupMenu(); }
From source file:net.olejon.spotcommander.WebViewActivity.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Google API client mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApiIfAvailable(Wearable.API).build(); // Allow landscape? if (!mTools.allowLandscape()) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Hide status bar? if (mTools.getDefaultSharedPreferencesBoolean("HIDE_STATUS_BAR")) getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Power manager final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); //noinspection deprecation mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock"); // Settings//w ww .j ava2 s. c om mTools.setSharedPreferencesBoolean("CAN_CLOSE_COVER", false); // Current network mCurrentNetwork = mTools.getCurrentNetwork(); // Computer final long computerId = mTools.getSharedPreferencesLong("LAST_COMPUTER_ID"); final String[] computer = mTools.getComputer(computerId); final String uri = computer[0]; final String username = computer[1]; final String password = computer[2]; // Layout setContentView(R.layout.activity_webview); // Status bar color if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mStatusBarPrimaryColor = getWindow().getStatusBarColor(); mStatusBarCoverArtColor = mStatusBarPrimaryColor; } // Notification mPersistentNotificationIsSupported = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN); if (mPersistentNotificationIsSupported) { final Intent launchActivityIntent = new Intent(mContext, MainActivity.class); launchActivityIntent.setAction("android.intent.action.MAIN"); launchActivityIntent.addCategory("android.intent.category.LAUNCHER"); mLaunchActivityPendingIntent = PendingIntent.getActivity(mContext, 0, launchActivityIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent hideIntent = new Intent(mContext, RemoteControlIntentService.class); hideIntent.setAction("hide_notification"); hideIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mHidePendingIntent = PendingIntent.getService(mContext, 0, hideIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent previousIntent = new Intent(mContext, RemoteControlIntentService.class); previousIntent.setAction("previous"); previousIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mPreviousPendingIntent = PendingIntent.getService(mContext, 0, previousIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent playPauseIntent = new Intent(mContext, RemoteControlIntentService.class); playPauseIntent.setAction("play_pause"); playPauseIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mPlayPausePendingIntent = PendingIntent.getService(mContext, 0, playPauseIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent nextIntent = new Intent(mContext, RemoteControlIntentService.class); nextIntent.setAction("next"); nextIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mNextPendingIntent = PendingIntent.getService(mContext, 0, nextIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent volumeDownIntent = new Intent(mContext, RemoteControlIntentService.class); volumeDownIntent.setAction("adjust_spotify_volume_down"); volumeDownIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mVolumeDownPendingIntent = PendingIntent.getService(mContext, 0, volumeDownIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent volumeUpIntent = new Intent(mContext, RemoteControlIntentService.class); volumeUpIntent.setAction("adjust_spotify_volume_up"); volumeUpIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mVolumeUpPendingIntent = PendingIntent.getService(mContext, 0, volumeUpIntent, PendingIntent.FLAG_CANCEL_CURRENT); mNotificationManager = NotificationManagerCompat.from(mContext); mNotificationBuilder = new NotificationCompat.Builder(mContext); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) mNotificationBuilder.setPriority(Notification.PRIORITY_MAX); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); mNotificationBuilder.setCategory(Notification.CATEGORY_TRANSPORT); } } // Web view mWebView = (WebView) findViewById(R.id.webview_webview); mWebView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background)); mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY); mWebView.setWebViewClient(new WebViewClient() { @SuppressWarnings("deprecation") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null && !url.contains(uri) && !url.contains("olejon.net/code/spotcommander/api/1/spotify/") && !url.contains("accounts.spotify.com/") && !url.contains("facebook.com/")) { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } return false; } @Override public void onReceivedHttpAuthRequest(WebView view, @NonNull HttpAuthHandler handler, String host, String realm) { if (handler.useHttpAuthUsernamePassword()) { handler.proceed(username, password); } else { handler.cancel(); mWebView.stopLoading(); mTools.showToast(getString(R.string.webview_authentication_failed), 1); mTools.navigateUp(mActivity); } } @Override public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) { mWebView.stopLoading(); mTools.showToast(getString(R.string.webview_error), 1); mTools.navigateUp(mActivity); } @Override public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) { handler.cancel(); mWebView.stopLoading(); new MaterialDialog.Builder(mContext).title(R.string.webview_dialog_ssl_error_title) .content(getString(R.string.webview_dialog_ssl_error_message)) .positiveText(R.string.webview_dialog_ssl_error_positive_button) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { finish(); } }).contentColorRes(R.color.black).show(); } }); // User agent mProjectVersionName = mTools.getProjectVersionName(); final String uaAppend1 = (!username.equals("") && !password.equals("")) ? "AUTHENTICATION_ENABLED " : ""; final String uaAppend2 = (mTools.getSharedPreferencesBoolean("WEAR_CONNECTED")) ? "WEAR_CONNECTED " : ""; final String uaAppend3 = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && !mTools.getDefaultSharedPreferencesBoolean("HARDWARE_ACCELERATED_ANIMATIONS")) ? "DISABLE_CSSTRANSITIONS DISABLE_CSSTRANSFORMS3D " : ""; // Web settings final WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); webSettings.setUserAgentString(getString(R.string.webview_user_agent, webSettings.getUserAgentString(), mProjectVersionName, uaAppend1, uaAppend2, uaAppend3)); // Load app if (savedInstanceState != null) { mWebView.restoreState(savedInstanceState); } else { mWebView.loadUrl(uri); } // JavaScript interface mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android"); }
From source file:mgks.os.webview.MainActivity.java
@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" }) @Override/* w ww. jav a 2 s . c o m*/ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.w("READ_PERM = ", Manifest.permission.READ_EXTERNAL_STORAGE); Log.w("WRITE_PERM = ", Manifest.permission.WRITE_EXTERNAL_STORAGE); //Prevent the app from being started again when it is still alive in the background if (!isTaskRoot()) { finish(); return; } setContentView(R.layout.activity_main); asw_view = findViewById(R.id.msw_view); final SwipeRefreshLayout pullfresh = findViewById(R.id.pullfresh); if (ASWP_PULLFRESH) { pullfresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { pull_fresh(); pullfresh.setRefreshing(false); } }); asw_view.getViewTreeObserver() .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (asw_view.getScrollY() == 0) { pullfresh.setEnabled(true); } else { pullfresh.setEnabled(false); } } }); } else { pullfresh.setRefreshing(false); pullfresh.setEnabled(false); } if (ASWP_PBAR) { asw_progress = findViewById(R.id.msw_progress); } else { findViewById(R.id.msw_progress).setVisibility(View.GONE); } asw_loading_text = findViewById(R.id.msw_loading_text); Handler handler = new Handler(); //Launching app rating request if (ASWP_RATINGS) { handler.postDelayed(new Runnable() { public void run() { get_rating(); } }, 1000 * 60); //running request after few moments } //Getting basic device information get_info(); //Getting GPS location of device if given permission if (ASWP_LOCATION && !check_permission(1)) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm); } get_location(); //Webview settings; defaults are customized for best performance WebSettings webSettings = asw_view.getSettings(); if (!ASWP_OFFLINE) { webSettings.setJavaScriptEnabled(ASWP_JSCRIPT); } webSettings.setSaveFormData(ASWP_SFORM); webSettings.setSupportZoom(ASWP_ZOOM); webSettings.setGeolocationEnabled(ASWP_LOCATION); webSettings.setAllowFileAccess(true); webSettings.setAllowFileAccessFromFileURLs(true); webSettings.setAllowUniversalAccessFromFileURLs(true); webSettings.setUseWideViewPort(true); webSettings.setDomStorageEnabled(true); asw_view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); asw_view.setHapticFeedbackEnabled(false); asw_view.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) { if (!check_permission(2)) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, file_perm); } else { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setMimeType(mimeType); String cookies = CookieManager.getInstance().getCookie(url); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); request.setDescription(getString(R.string.dl_downloading)); request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType)); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); assert dm != null; dm.enqueue(request); Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG) .show(); } } }); if (Build.VERSION.SDK_INT >= 21) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null); webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } else if (Build.VERSION.SDK_INT >= 19) { asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null); } asw_view.setVerticalScrollBarEnabled(false); asw_view.setWebViewClient(new Callback()); //Rendering the default URL aswm_view(ASWV_URL, false); asw_view.setWebChromeClient(new WebChromeClient() { //Handling input[type="file"] requests for android API 16+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { if (ASWP_FUPLOAD) { asw_file_message = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(ASWV_F_TYPE); if (ASWP_MULFILE) { i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req); } } //Handling input[type="file"] requests for android API 21+ public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (check_permission(2) && check_permission(3)) { if (ASWP_FUPLOAD) { if (asw_file_path != null) { asw_file_path.onReceiveValue(null); } asw_file_path = filePathCallback; Intent takePictureIntent = null; if (ASWP_CAMUPLOAD) { takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) { File photoFile = null; try { photoFile = create_image(); takePictureIntent.putExtra("PhotoPath", asw_cam_message); } catch (IOException ex) { Log.e(TAG, "Image file creation failed", ex); } if (photoFile != null) { asw_cam_message = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); } else { takePictureIntent = null; } } } Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); if (!ASWP_ONLYCAM) { contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType(ASWV_F_TYPE); if (ASWP_MULFILE) { contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } } Intent[] intentArray; if (takePictureIntent != null) { intentArray = new Intent[] { takePictureIntent }; } else { intentArray = new Intent[0]; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser)); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, asw_file_req); } return true; } else { get_file(); return false; } } //Getting webview rendering progress @Override public void onProgressChanged(WebView view, int p) { if (ASWP_PBAR) { asw_progress.setProgress(p); if (p == 100) { asw_progress.setProgress(0); } } } // overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { if (Build.VERSION.SDK_INT < 23 || check_permission(1)) { // location permissions were granted previously so auto-approve callback.invoke(origin, true, false); } else { // location permissions not granted so request them ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm); } } }); if (getIntent().getData() != null) { String path = getIntent().getDataString(); /* If you want to check or use specific directories or schemes or hosts Uri data = getIntent().getData(); String scheme = data.getScheme(); String host = data.getHost(); List<String> pr = data.getPathSegments(); String param1 = pr.get(0); */ aswm_view(path, false); } }
From source file:net.bluecarrot.lite.MainActivity.java
private void setUpWebViewDefaults(WebView webView) { WebSettings settings = webView.getSettings(); //allow Geolocation settings.setGeolocationEnabled(savedPreferences.getBoolean("pref_allowGeolocation", true)); // Enable Javascript settings.setJavaScriptEnabled(true); //to make the webview faster //settings.setCacheMode(WebSettings.LOAD_NO_CACHE); // Use WideViewport and Zoom out if there is no viewport defined settings.setUseWideViewPort(true);/*from w w w.j a v a2s . c o m*/ settings.setLoadWithOverviewMode(true); // better image sizing support settings.setSupportZoom(true); settings.setDisplayZoomControls(false); settings.setBuiltInZoomControls(true); settings.setGeolocationDatabasePath(getBaseContext().getFilesDir().getPath()); settings.setLoadsImagesAutomatically(!savedPreferences.getBoolean("pref_doNotDownloadImages", false));//to save data //todo setLoadsImagesAutomatically without restart the app // Enable pinch to zoom without the zoom buttons settings.setBuiltInZoomControls(true); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { // Hide the zoom controls for HONEYCOMB+ settings.setDisplayZoomControls(false); } // Enable remote debugging via chrome://inspect if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } }
From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java
private void setWebView(final GalleryItemViewTag tag, final File file) { runOnUiThread(new Runnable() { private boolean oomFlag = false; private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); private void prepareWebView(WebView webView) { webView.setBackgroundColor(Color.TRANSPARENT); webView.setInitialScale(100); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { CompatibilityImpl.setScrollbarFadingEnabled(webView, true); }/*ww w .ja v a 2 s . c o m*/ WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setSupportZoom(true); settings.setAllowFileAccess(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { CompatibilityImpl.setDefaultZoomFAR(settings); CompatibilityImpl.setLoadWithOverviewMode(settings, true); } settings.setUseWideViewPort(true); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { CompatibilityImpl.setBlockNetworkLoads(settings, true); } setScaleWebView(webView); } private void setScaleWebView(final WebView webView) { Runnable callSetScaleWebView = new Runnable() { @Override public void run() { setPrivateScaleWebView(webView); } }; Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); if (resolution.equals(0, 0)) { // wait until the view is measured and its size is known AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView); } else { callSetScaleWebView.run(); } } private void setPrivateScaleWebView(WebView webView) { Point imageSize = getImageSize(file); Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y); double scaleX = (double) resolution.x / (double) imageSize.x; double scaleY = (double) resolution.y / (double) imageSize.y; int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d); scale = Math.max(scale, 1); //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX; if (picdpi >= 240) { CompatibilityImpl.setDefaultZoomFAR(webView.getSettings()); } else if (picdpi <= 120) { CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings()); } else { CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings()); } } webView.setInitialScale(scale); webView.setPadding(0, 0, 0, 0); } private Point getImageSize(File file) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); return new Point(options.outWidth, options.outHeight); } private boolean useFallback(File file) { String path = file.getPath().toLowerCase(Locale.US); if (path.endsWith(".png")) return false; if (path.endsWith(".jpg")) return false; if (path.endsWith(".gif")) return false; if (path.endsWith(".jpeg")) return false; if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) return false; return true; } @Override public void run() { try { recycleTag(tag, false); WebView webView = new WebViewFixed(GalleryActivity.this); webView.setLayoutParams(MATCH_PARAMS); tag.layout.addView(webView); if (settings.fallbackWebView() || useFallback(file)) { prepareWebView(webView); webView.loadUrl(Uri.fromFile(file).toString()); } else { JSWebView.setImage(webView, file); } tag.thumbnailView.setVisibility(View.GONE); tag.loadingView.setVisibility(View.GONE); tag.layout.setVisibility(View.VISIBLE); } catch (OutOfMemoryError oom) { System.gc(); Logger.e(TAG, oom); if (!oomFlag) { oomFlag = true; run(); } else showError(tag, getString(R.string.error_out_of_memory)); } } }); }
From source file:nya.miku.wishmaster.ui.GalleryActivity.java
private void setWebView(final GalleryItemViewTag tag, final File file) { runOnUiThread(new Runnable() { private boolean oomFlag = false; private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); private void prepareWebView(WebView webView) { webView.setBackgroundColor(Color.TRANSPARENT); webView.setInitialScale(100); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { CompatibilityImpl.setScrollbarFadingEnabled(webView, true); }//w w w .ja va2 s. c o m WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setSupportZoom(true); settings.setAllowFileAccess(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { CompatibilityImpl.setDefaultZoomFAR(settings); CompatibilityImpl.setLoadWithOverviewMode(settings, true); } settings.setUseWideViewPort(true); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { CompatibilityImpl.setBlockNetworkLoads(settings, true); } setScaleWebView(webView); } private void setScaleWebView(final WebView webView) { Runnable callSetScaleWebView = new Runnable() { @Override public void run() { setPrivateScaleWebView(webView); } }; Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); if (resolution.equals(0, 0)) { // wait until the view is measured and its size is known AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView); } else { callSetScaleWebView.run(); } } private void setPrivateScaleWebView(WebView webView) { Point imageSize = getImageSize(file); Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y); double scaleX = (double) resolution.x / (double) imageSize.x; double scaleY = (double) resolution.y / (double) imageSize.y; int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d); scale = Math.max(scale, 1); //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX; if (picdpi >= 240) { CompatibilityImpl.setDefaultZoomFAR(webView.getSettings()); } else if (picdpi <= 120) { CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings()); } else { CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings()); } } webView.setInitialScale(scale); webView.setPadding(0, 0, 0, 0); } private Point getImageSize(File file) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); return new Point(options.outWidth, options.outHeight); } private boolean useFallback(File file) { String path = file.getPath().toLowerCase(Locale.US); if (path.endsWith(".png")) return false; if (path.endsWith(".jpg")) return false; if (path.endsWith(".gif")) return false; if (path.endsWith(".jpeg")) return false; if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) return false; return true; } @Override public void run() { try { recycleTag(tag, false); WebView webView = new WebViewFixed(GalleryActivity.this); webView.setLayoutParams(MATCH_PARAMS); tag.layout.addView(webView); if (settings.fallbackWebView() || useFallback(file)) { prepareWebView(webView); webView.loadUrl(Uri.fromFile(file).toString()); } else { JSWebView.setImage(webView, file); } tag.thumbnailView.setVisibility(View.GONE); tag.loadingView.setVisibility(View.GONE); tag.layout.setVisibility(View.VISIBLE); } catch (OutOfMemoryError oom) { MainApplication.freeMemory(); Logger.e(TAG, oom); if (!oomFlag) { oomFlag = true; run(); } else showError(tag, getString(R.string.error_out_of_memory)); } } }); }
From source file:com.slarker.tech.hi0734.view.widget.webview.AdvancedWebView.java
public void setDesktopMode(final boolean enabled) { final WebSettings webSettings = getSettings(); final String newUserAgent; if (enabled) { newUserAgent = webSettings.getUserAgentString().replace("Mobile", "eliboM").replace("Android", "diordnA"); } else {/* w w w . jav a 2 s . c o m*/ newUserAgent = webSettings.getUserAgentString().replace("eliboM", "Mobile").replace("diordnA", "Android"); } webSettings.setUserAgentString(newUserAgent); webSettings.setUseWideViewPort(enabled); webSettings.setLoadWithOverviewMode(enabled); webSettings.setSupportZoom(enabled); webSettings.setBuiltInZoomControls(enabled); }
From source file:com.android.mail.ui.ConversationViewFragment.java
private void setupOverviewMode() { // for now, overview mode means use the built-in WebView zoom and disable custom scale // gesture handling final boolean overviewMode = isOverviewMode(mAccount); final WebSettings settings = mWebView.getSettings(); final WebSettings.LayoutAlgorithm layout; settings.setUseWideViewPort(overviewMode); settings.setSupportZoom(overviewMode); settings.setBuiltInZoomControls(overviewMode); settings.setLoadWithOverviewMode(overviewMode); if (overviewMode) { settings.setDisplayZoomControls(false); layout = WebSettings.LayoutAlgorithm.NORMAL; } else {/* w w w .j ava 2s .c om*/ layout = WebSettings.LayoutAlgorithm.NARROW_COLUMNS; } settings.setLayoutAlgorithm(layout); }
From source file:cn.suishen.email.activity.MessageViewFragmentBase.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Logging.LOG_TAG, this + " onCreateView"); }/*from w ww . ja v a 2 s . c o m*/ final View view = inflater.inflate(R.layout.message_view_fragment, container, false); cleanupDetachedViews(); mSubjectView = (TextView) UiUtilities.getView(view, R.id.subject); mFromNameView = (TextView) UiUtilities.getView(view, R.id.from_name); mFromAddressView = (TextView) UiUtilities.getView(view, R.id.from_address); mAddressesView = (TextView) UiUtilities.getView(view, R.id.addresses); mDateTimeView = (TextView) UiUtilities.getView(view, R.id.datetime); mMessageContentView = (WebView) UiUtilities.getView(view, R.id.message_content); mAttachments = (LinearLayout) UiUtilities.getView(view, R.id.attachments); mTabSection = UiUtilities.getView(view, R.id.message_tabs_section); mFromBadge = (ImageView) UiUtilities.getView(view, R.id.badge); mSenderPresenceView = (ImageView) UiUtilities.getView(view, R.id.presence); mMainView = UiUtilities.getView(view, R.id.main_panel); mLoadingProgress = UiUtilities.getView(view, R.id.loading_progress); mDetailsCollapsed = UiUtilities.getView(view, R.id.sub_header_contents_collapsed); mDetailsExpanded = UiUtilities.getView(view, R.id.sub_header_contents_expanded); mFromNameView.setOnClickListener(this); mFromAddressView.setOnClickListener(this); mFromBadge.setOnClickListener(this); mSenderPresenceView.setOnClickListener(this); mMessageTab = UiUtilities.getView(view, R.id.show_message); mAttachmentTab = UiUtilities.getView(view, R.id.show_attachments); mShowPicturesTab = UiUtilities.getView(view, R.id.show_pictures); mAlwaysShowPicturesButton = UiUtilities.getView(view, R.id.always_show_pictures_button); // Invite is only used in MessageViewFragment, but visibility is controlled here. mInviteTab = UiUtilities.getView(view, R.id.show_invite); mMessageTab.setOnClickListener(this); mAttachmentTab.setOnClickListener(this); mShowPicturesTab.setOnClickListener(this); mAlwaysShowPicturesButton.setOnClickListener(this); mInviteTab.setOnClickListener(this); mDetailsCollapsed.setOnClickListener(this); mDetailsExpanded.setOnClickListener(this); mAttachmentsScroll = UiUtilities.getView(view, R.id.attachments_scroll); mInviteScroll = UiUtilities.getView(view, R.id.invite_scroll); WebSettings webSettings = mMessageContentView.getSettings(); boolean supportMultiTouch = mContext.getPackageManager() .hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH); webSettings.setDisplayZoomControls(!supportMultiTouch); webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); mMessageContentView.setWebViewClient(new CustomWebViewClient()); return view; }
From source file:com.acrutiapps.browser.ui.components.CustomWebView.java
@SuppressLint("SetJavaScriptEnabled") public void loadSettings() { WebSettings settings = getSettings(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); settings.setJavaScriptEnabled(prefs.getBoolean(Constants.PREFERENCE_ENABLE_JAVASCRIPT, true)); settings.setLoadsImagesAutomatically(prefs.getBoolean(Constants.PREFERENCE_ENABLE_IMAGES, true)); settings.setUseWideViewPort(prefs.getBoolean(Constants.PREFERENCE_USE_WIDE_VIEWPORT, true)); settings.setLoadWithOverviewMode(prefs.getBoolean(Constants.PREFERENCE_LOAD_WITH_OVERVIEW, false)); settings.setGeolocationEnabled(prefs.getBoolean(Constants.PREFERENCE_ENABLE_GEOLOCATION, true)); settings.setSaveFormData(prefs.getBoolean(Constants.PREFERENCE_REMEMBER_FORM_DATA, true)); settings.setSavePassword(prefs.getBoolean(Constants.PREFERENCE_REMEMBER_PASSWORDS, true)); settings.setTextZoom(prefs.getInt(Constants.PREFERENCE_TEXT_SCALING, 100)); int minimumFontSize = prefs.getInt(Constants.PREFERENCE_MINIMUM_FONT_SIZE, 1); settings.setMinimumFontSize(minimumFontSize); settings.setMinimumLogicalFontSize(minimumFontSize); boolean useInvertedDisplay = prefs.getBoolean(Constants.PREFERENCE_INVERTED_DISPLAY, false); setWebSettingsProperty(settings, "inverted", useInvertedDisplay ? "true" : "false"); if (useInvertedDisplay) { setWebSettingsProperty(settings, "inverted_contrast", Float.toString(prefs.getInt(Constants.PREFERENCE_INVERTED_DISPLAY_CONTRAST, 100) / 100f)); }/* ww w . ja va2s. co m*/ settings.setUserAgentString(prefs.getString(Constants.PREFERENCE_USER_AGENT, Constants.USER_AGENT_ANDROID)); settings.setPluginState(PluginState .valueOf(prefs.getString(Constants.PREFERENCE_PLUGINS, PluginState.ON_DEMAND.toString()))); CookieManager.getInstance().setAcceptCookie(prefs.getBoolean(Constants.PREFERENCE_ACCEPT_COOKIES, true)); settings.setSupportZoom(true); settings.setDisplayZoomControls(false); settings.setBuiltInZoomControls(true); settings.setSupportMultipleWindows(true); settings.setEnableSmoothTransition(true); if (mPrivateBrowsing) { settings.setGeolocationEnabled(false); settings.setSaveFormData(false); settings.setSavePassword(false); settings.setAppCacheEnabled(false); settings.setDatabaseEnabled(false); settings.setDomStorageEnabled(false); } else { // HTML5 API flags settings.setAppCacheEnabled(true); settings.setDatabaseEnabled(true); settings.setDomStorageEnabled(true); // HTML5 configuration settings. settings.setAppCacheMaxSize(3 * 1024 * 1024); settings.setAppCachePath(mContext.getDir("appcache", 0).getPath()); settings.setDatabasePath(mContext.getDir("databases", 0).getPath()); settings.setGeolocationDatabasePath(mContext.getDir("geolocation", 0).getPath()); } setLongClickable(true); setDownloadListener(this); }