List of usage examples for android.webkit WebSettings setJavaScriptEnabled
public abstract void setJavaScriptEnabled(boolean flag);
From source file:net.evecom.android.web.Web0Activity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; temp = HttpUtil.getPageSize(this); setContentView(R.layout.message_post_web); imageView = (ImageView) findViewById(R.id.image_view_at_web); webView = (WebView) this.findViewById(R.id.wv_oauth_message); CookieSyncManager.createInstance(this); CookieSyncManager.getInstance().startSync(); CookieManager.getInstance().removeSessionCookie(); /**/*from w w w . j a va 2s . c o m*/ * WebViewJavaScript */ webView.getSettings().setJavaScriptEnabled(true); /** * loadUrl() */ webView.setWebViewClient(new HelloWebViewClient()); dialog = ProgressDialog.show(Web0Activity.this, null, ".."); dialog.setCancelable(true); // http://harlan-pc/fzaj/emergency/mobileWebApp/publicInfo/login.do?userName=zf1&userPwd=1 // webView.loadUrl("http://www.baidu.com"); // String url = HttpUtil.BASE_PC_URL // String url =HttpUtil.BASE_PC_URL+"loginController/messageLogin"; String url = HttpUtil.BASE_PC_URL + "mobile/loginController/messageLogin"; // post String postDate = "loginname=" + ShareUtil.getString(getApplicationContext(), "SESSION", "USERNAME", "") + "&pwd=" + ShareUtil.getString(getApplicationContext(), "SESSION", "PASSWORD", "") + "&pageSize=" + temp; // webView.postUrl(url, postData) postDatabyte[] // EncodingUtils.getBytes(data, charset) webView.postUrl(url, EncodingUtils.getBytes(postDate, "BASE64")); // webView.setDownloadListener(new MyWebViewDownLoadListener()); WebSettings webSettings = webView.getSettings(); webSettings.setSupportZoom(true); webSettings.setJavaScriptEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); webSettings.setBuiltInZoomControls(true);// support zoom // webSettings.setPluginsEnabled(true);//support flash webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); /** */ // // webSettings.setDatabaseEnabled(true); String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); // webSettings.setGeolocationEnabled(true); // webSettings.setGeolocationDatabasePath(dir); // webSettings.setDomStorageEnabled(true); // webSettings.setPluginsEnabled(true); //(flash) DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int mDensity = metrics.densityDpi; // DebugLog.d(TAG, "densityDpi = " + mDensity); if (mDensity == 240) { webSettings.setDefaultZoom(ZoomDensity.FAR); } else if (mDensity == 160) { webSettings.setDefaultZoom(ZoomDensity.MEDIUM); } else if (mDensity == 120) { webSettings.setDefaultZoom(ZoomDensity.CLOSE); // }else if(mDensity == DisplayMetrics..DENSITY_XHIGH){ // webSettings.setDefaultZoom(ZoomDensity.FAR); } else if (mDensity == DisplayMetrics.DENSITY_HIGH) { webSettings.setDefaultZoom(ZoomDensity.FAR); } webView.setWebChromeClient(m_chromeClient);// (flash) dialogPress = new AlertDialog.Builder(this).setTitle("").setMessage(":0/0") .setPositiveButton("", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); }
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 w w. j a v a 2 s . c o m 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:io.selendroid.server.model.SelendroidWebDriver.java
private void configureWebView(final WebView view) { ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() { @Override/* ww w. j a va2s . com*/ public void run() { try { view.clearCache(true); view.clearFormData(); view.clearHistory(); view.setFocusable(true); view.setFocusableInTouchMode(true); view.setNetworkAvailable(true); // need to check the class name rather than checking instanceof // since when it is not an instanceof, it likely means the app under test // does not contain the Cordova project and this will cause a RuntimeException if (view.getClass().getSimpleName().equalsIgnoreCase("CordovaWebView")) { CordovaWebView webview = (CordovaWebView) view; CordovaInterface ci = null; chromeClient = new ExtendedCordovaChromeClient(null, webview); } else { chromeClient = new SelendroidWebChromeClient(); } view.setWebChromeClient(chromeClient); WebSettings settings = view.getSettings(); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setSupportMultipleWindows(true); settings.setBuiltInZoomControls(true); settings.setJavaScriptEnabled(true); settings.setAppCacheEnabled(true); settings.setAppCacheMaxSize(10 * 1024 * 1024); settings.setAppCachePath(""); settings.setDatabaseEnabled(true); settings.setDomStorageEnabled(true); settings.setGeolocationEnabled(true); settings.setSaveFormData(false); settings.setSavePassword(false); settings.setRenderPriority(WebSettings.RenderPriority.HIGH); // Flash settings settings.setPluginState(WebSettings.PluginState.ON); // Geo location settings settings.setGeolocationEnabled(true); settings.setGeolocationDatabasePath("/data/data/selendroid"); } catch (Exception e) { SelendroidLogger.error("Error configuring web view", e); } } }); }
From source file:com.rsltc.profiledata.main.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button loginButton = (Button) findViewById(R.id.button); loginButton.setOnClickListener(new View.OnClickListener() { @Override/*from w w w . jav a2 s. c o m*/ public void onClick(View v) { try { AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity); alert.setTitle("Title here"); StringBuilder query = new StringBuilder(); query.append("redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8")); query.append("&client_id=" + URLEncoder.encode(clientId, "utf-8")); query.append("&scope=" + URLEncoder.encode(scopes, "utf-8")); query.append("&response_type=code"); URI uri = new URI("https://login.live.com/oauth20_authorize.srf?" + query.toString()); URL url = uri.toURL(); final WebView wv = new WebView(thisActivity); WebSettings webSettings = wv.getSettings(); webSettings.setJavaScriptEnabled(true); wv.loadUrl(url.toString()); wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String location) { Log.e(TAG, location); // TODO: extract to method try { URL url = new URL(location); if (url.getPath().equalsIgnoreCase("/oauth20_desktop.srf")) { System.out.println("Dit werkt al!"); System.out.println(url.getQuery()); Map<String, List<String>> result = splitQuery(url); if (result.containsKey("code")) { System.out.println("bevat code"); if (result.containsKey("error")) { System.out.println(String.format("{0}\r\n{1}", result.get("error"), result.get("errorDesc"))); } System.out.println(result.get("code").get(0)); String tokenError = GetToken(result.get("code").get(0), false); if (tokenError == null || "".equals(tokenError)) { System.out.println("Successful sign-in!"); Log.e(TAG, "Successful sign-in!"); } else { Log.e(TAG, "tokenError: " + tokenError); } } else { System.out.println("Successful sign-out!"); } } } catch (IOException | URISyntaxException e) { e.printStackTrace(); } view.loadUrl(location); return true; } }); LinearLayout linearLayout = new LinearLayout(thisActivity); linearLayout.setMinimumHeight(500); ArrayList<View> views = new ArrayList<View>(); views.add(wv); linearLayout.addView(wv); EditText text = new EditText(thisActivity); text.setVisibility(View.GONE); linearLayout.addView(text); alert.setView(linearLayout); alert.setNegativeButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); alert.show(); } catch (Exception e) { Log.e(TAG, "dd"); } } }); Button showProfile = (Button) findViewById(R.id.button2); showProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProfile(); } }); Button showSummmary = (Button) findViewById(R.id.button3); showSummmary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSummaries(); } }); if (savedInstanceState != null) { authInProgress = savedInstanceState.getBoolean(AUTH_PENDING); } buildFitnessClient(); }
From source file:org.apache.cordova.InAppBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load. * @param jsonObject/*from w w w. j a v a 2 s. c om*/ */ public String showWebPage(final String url, HashMap<String, Boolean> features) { // Determine if we should hide the location bar. showLocationBar = true; openWindowHidden = false; if (features != null) { Boolean show = features.get(LOCATION); if (show != null) { showLocationBar = show.booleanValue(); } Boolean hidden = features.get(HIDDEN); if (hidden != null) { openWindowHidden = hidden.booleanValue(); } Boolean cache = features.get(CLEAR_ALL_CACHE); if (cache != null) { clearAllCache = cache.booleanValue(); } else { cache = features.get(CLEAR_SESSION_CACHE); if (cache != null) { clearSessionCache = cache.booleanValue(); } } } final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics()); return value; } public void run() { // Let's create the main dialog dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { closeDialog(); } }); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); //Please, no more black! toolbar.setBackgroundColor(android.graphics.Color.LTGRAY); toolbar.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(1); // Back button Button back = new Button(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(2); back.setText("<"); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button Button forward = new Button(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(3); forward.setText(">"); forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(4); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close button Button close = new Button(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(5); close.setText(buttonLabel); close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView)); WebViewClient client = new InAppBrowserClient(thatWebView, edittext); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(true); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext() .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (clearAllCache) { CookieManager.getInstance().removeAllCookie(); } else if (clearSessionCache) { CookieManager.getInstance().removeSessionCookie(); } inAppWebView.loadUrl(url); inAppWebView.setId(6); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(true); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(inAppWebView); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if (openWindowHidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }
From source file:ch.gianulli.flashcards.ui.Flashcard.java
/** * @param view Instance of flashcard.xml *///from w w w . ja va 2 s .c o m public Flashcard(View view, OnCardAnsweredListener listener) { mListener = listener; mView = view; mQuestion = (StyledMarkdownView) view.findViewById(R.id.question); mAnswer = (StyledMarkdownView) view.findViewById(R.id.answer); mCardView = (CardView) view.findViewById(R.id.card); mButtonBar = view.findViewById(R.id.button_bar); mCorrectButton = (Button) view.findViewById(R.id.correct_button); mWrongButton = (Button) view.findViewById(R.id.wrong_button); mContext = mView.getContext(); // Load colors int[] attrs = { android.R.attr.textColorSecondary, android.R.attr.textColorPrimary }; TypedArray ta = mView.getContext().obtainStyledAttributes(R.style.AppTheme, attrs); sDeactivatedTextColor = colorToCSSString(ta.getColor(0, 0)); sDefaultTextColor = colorToCSSString(ta.getColor(1, 0)); ta.recycle(); sGreenTextColor = colorToCSSString(ContextCompat.getColor(mContext, R.color.green)); mQuestionColor = sDefaultTextColor; mAnswerColor = sGreenTextColor; // Make question visible mQuestion.setAlpha(1.0f); mAnswer.setAlpha(0.0f); // Setup WebViews WebSettings settings = mQuestion.getSettings(); settings.setDefaultFontSize(mFontSize); settings.setLoadsImagesAutomatically(true); settings.setGeolocationEnabled(false); settings.setAllowFileAccess(false); settings.setDisplayZoomControls(false); settings.setNeedInitialFocus(false); settings.setSupportZoom(false); settings.setSaveFormData(false); settings.setJavaScriptEnabled(true); mQuestion.setHorizontalScrollBarEnabled(false); mQuestion.setVerticalScrollBarEnabled(false); settings = mAnswer.getSettings(); settings.setDefaultFontSize(mFontSize); settings.setLoadsImagesAutomatically(true); settings.setGeolocationEnabled(false); settings.setAllowFileAccess(false); settings.setDisplayZoomControls(false); settings.setNeedInitialFocus(false); settings.setSupportZoom(false); settings.setSaveFormData(false); settings.setJavaScriptEnabled(true); mAnswer.setHorizontalScrollBarEnabled(false); mAnswer.setVerticalScrollBarEnabled(false); // Hack to disable text selection in WebViews mQuestion.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { return true; } }); mAnswer.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { return true; } }); // Card should "turn" on click final FrameLayout questionLayout = (FrameLayout) view.findViewById(R.id.question_layout); questionLayout.setClickable(true); questionLayout.setOnTouchListener(mTurnCardListener); mQuestion.setOnTouchListener(mTurnCardListener); mAnswer.setOnTouchListener(mTurnCardListener); // Deactivate card when user answers it mCorrectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deactivateCard(true); mListener.onCardAnswered(mCard, true); } }); mWrongButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deactivateCard(false); mListener.onCardAnswered(mCard, false); } }); // Limit card width to 400dp ViewTreeObserver observer = mCardView.getViewTreeObserver(); final int width480dp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 400, view.getContext().getResources().getDisplayMetrics()); observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (mCardView.getWidth() > width480dp) { ViewGroup.LayoutParams layoutParams = mCardView.getLayoutParams(); layoutParams.width = width480dp; mCardView.setLayoutParams(layoutParams); mCardView.requestLayout(); return false; } return true; } }); }
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 a 2 s.co 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:org.apache.cordova.core.InAppBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load. * @param jsonObject//from w w w . j a v a2 s. c o m */ public String showWebPage(final String url, HashMap<String, Boolean> features) { // Determine if we should hide the location bar. showLocationBar = true; openWindowHidden = false; if (features != null) { Boolean show = features.get(LOCATION); if (show != null) { showLocationBar = show.booleanValue(); } Boolean hidden = features.get(HIDDEN); if (hidden != null) { openWindowHidden = hidden.booleanValue(); } } final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics()); return value; } public void run() { // Let's create the main dialog dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { try { JSONObject obj = new JSONObject(); obj.put("type", EXIT_EVENT); sendUpdate(obj, false); } catch (JSONException e) { Log.d(LOG_TAG, "Should never happen"); } } }); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); toolbar.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(1); // Back button Button back = new Button(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(2); back.setText("<"); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button Button forward = new Button(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(3); forward.setText(">"); forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(4); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close button Button close = new Button(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(5); close.setText(buttonLabel); close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView)); WebViewClient client = new InAppBrowserClient(thatWebView, edittext); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(true); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext() .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); inAppWebView.loadUrl(url); inAppWebView.setId(6); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(true); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(inAppWebView); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if (openWindowHidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }
From source file:mgks.os.webview.MainActivity.java
@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" }) @Override//from w ww . jav a 2 s. co 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:com.neka.cordova.inappbrowser.InAppBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load. * @param jsonObject//from w w w .j av a 2 s . com */ public String showWebPage(final String url, HashMap<String, Boolean> features) { // Determine if we should hide the location bar. showLocationBar = true; openWindowHidden = false; if (features != null) { Boolean show = features.get(LOCATION); if (show != null) { showLocationBar = show.booleanValue(); } Boolean hidden = features.get(HIDDEN); if (hidden != null) { openWindowHidden = hidden.booleanValue(); } Boolean cache = features.get(CLEAR_ALL_CACHE); if (cache != null) { clearAllCache = cache.booleanValue(); } else { cache = features.get(CLEAR_SESSION_CACHE); if (cache != null) { clearSessionCache = cache.booleanValue(); } } } final CordovaWebView thatWebView = this.webView; // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics()); return value; } public void run() { // Let's create the main dialog dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setInAppBroswer(getInAppBrowser()); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); //Please, no more black! toolbar.setBackgroundColor(android.graphics.Color.LTGRAY); toolbar.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(1); // Back button Button back = new Button(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(2); /* back.setText("<"); */ Resources activityRes = cordova.getActivity().getResources(); int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName()); Drawable backIcon = activityRes.getDrawable(backResId); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) { back.setBackgroundDrawable(backIcon); } else { back.setBackground(backIcon); } back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button Button forward = new Button(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(3); //forward.setText(">"); int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName()); Drawable fwdIcon = activityRes.getDrawable(fwdResId); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) { forward.setBackgroundDrawable(fwdIcon); } else { forward.setBackground(fwdIcon); } forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(4); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close button Button close = new Button(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(5); //close.setText(buttonLabel); int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName()); Drawable closeIcon = activityRes.getDrawable(closeResId); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) { close.setBackgroundDrawable(closeIcon); } else { close.setBackground(closeIcon); } close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView inAppWebView = new WebView(cordova.getActivity()); inAppWebView.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView)); WebViewClient client = new InAppBrowserClient(thatWebView, edittext); inAppWebView.setWebViewClient(client); WebSettings settings = inAppWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(true); settings.setPluginState(android.webkit.WebSettings.PluginState.ON); //Toggle whether this is enabled or not! Bundle appSettings = cordova.getActivity().getIntent().getExtras(); boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true); if (enableDatabase) { String databasePath = cordova.getActivity().getApplicationContext() .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); settings.setDatabaseEnabled(true); } settings.setDomStorageEnabled(true); if (clearAllCache) { CookieManager.getInstance().removeAllCookie(); } else if (clearSessionCache) { CookieManager.getInstance().removeSessionCookie(); } inAppWebView.loadUrl(url); inAppWebView.setId(6); inAppWebView.getSettings().setLoadWithOverviewMode(true); inAppWebView.getSettings().setUseWideViewPort(true); inAppWebView.requestFocus(); inAppWebView.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar //toolbar.addView(actionButtonContainer); //toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(inAppWebView); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); // the goal of openhidden is to load the url and not display it // Show() needs to be called to cause the URL to be loaded if (openWindowHidden) { dialog.hide(); } } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }