Example usage for android.widget FrameLayout removeAllViews

List of usage examples for android.widget FrameLayout removeAllViews

Introduction

In this page you can find the example usage for android.widget FrameLayout removeAllViews.

Prototype

public void removeAllViews() 

Source Link

Document

Call this method to remove all child views from the ViewGroup.

Usage

From source file:it.unipr.ce.dsg.gamidroid.activities.NAM4JAndroidActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    context = this;

    isTablet = Utils.isTablet(this);

    // Setting the default network
    sharedPreferences = getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE);
    Editor editor = sharedPreferences.edit();
    editor.putString(Constants.NETWORK, Constants.DEFAULT_NETWORK);
    editor.commit();//from   w w  w.j a  va  2  s. c om

    // Starting the resources monitoring service
    startService(new Intent(this, DeviceMonitorService.class));

    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    // Settings menu elements
    ArrayList<MenuListElement> listElements = new ArrayList<MenuListElement>();

    listElements.add(new MenuListElement(getResources().getString(R.string.connectMenuTitle),
            getResources().getString(R.string.connectMenuSubTitle)));
    listElements.add(new MenuListElement(getResources().getString(R.string.settingsMenuTitle),
            getResources().getString(R.string.settingsMenuSubTitle)));
    listElements.add(new MenuListElement(getResources().getString(R.string.exitMenuTitle),
            getResources().getString(R.string.exitMenuSubTitle)));

    listView = (ListView) findViewById(R.id.ListViewContent);

    MenuListAdapter adapter = new MenuListAdapter(this, R.layout.menu_list_view_row, listElements);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new ListItemClickListener());

    mainRL = (RelativeLayout) findViewById(R.id.rlContainer);
    listRL = (RelativeLayout) findViewById(R.id.listContainer);

    cpuBar = (LinearLayout) findViewById(R.id.CpuBar);
    memoryBar = (LinearLayout) findViewById(R.id.MemoryBar);

    titleBarRL = (RelativeLayout) findViewById(R.id.titleLl);

    // Adding swipe gesture listener to the top bar
    titleBarRL.setOnTouchListener(new SwipeAndClickListener());

    menuButton = (Button) findViewById(R.id.menuButton);
    menuButton.setOnTouchListener(new SwipeAndClickListener());

    infoButton = (Button) findViewById(R.id.infoButton);
    infoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            AlertDialog dialog = new AlertDialog(NAM4JAndroidActivity.this) {

                @Override
                public boolean dispatchTouchEvent(MotionEvent event) {
                    dismiss();
                    return false;
                }

            };

            String text = getResources().getString(R.string.aboutApp);
            String title = getResources().getString(R.string.nam4j);

            dialog.setMessage(text);
            dialog.setTitle(title);
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
        }
    });

    centerButton = (Button) findViewById(R.id.centerButton);
    centerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            centerMap();
        }
    });

    isTablet = Utils.isTablet(context);

    int[] screenSize = Utils.getScreenSize(context, getWindow());
    screenWidth = screenSize[0];
    screenHeight = screenSize[1];

    // Updates the display orientation each time the device is rotated
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        screenOrientation = Orientation.LANDSCAPE;
    } else {
        screenOrientation = Orientation.PORTRAIT;
    }

    // If the device is portrait, the menu button is displayed, the menu is
    // hidden and the swipe listener is added to the menu bar
    if (screenOrientation == Orientation.PORTRAIT) {

        menuButton.setVisibility(View.VISIBLE);

        // Adding swipe gesture listener to the top bar
        titleBarRL.setOnTouchListener(new SwipeAndClickListener());

        if (isTablet) {
            menuWidth = 0.35;
        } else {
            menuWidth = 0.6;
        }
    } else {
        // If the device is a tablet in landscape, the menu button is
        // hidden, the menu is displayed, the swipe listener is not added to
        // the menu bar and the mainRL width is set to the window's width
        // minus the menu's width
        if (isTablet) {
            menuWidth = 0.2;
            menuButton.setVisibility(View.INVISIBLE);

            RelativeLayout.LayoutParams menuListLP = (LayoutParams) mainRL.getLayoutParams();

            // Setting the main view width as the container width without
            // the menu
            menuListLP.width = (int) (screenWidth * (1 - menuWidth));
            mainRL.setLayoutParams(menuListLP);

            displaySideMenu();
        } else {
            menuWidth = 0.4;
            menuButton.setVisibility(View.VISIBLE);

            // Adding swipe gesture listener to the top bar
            titleBarRL.setOnTouchListener(new SwipeAndClickListener());
        }
    }

    // Check if the device has the Google Play Services installed and
    // updated. They are necessary to use Google Maps
    int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);

    if (code != ConnectionResult.SUCCESS) {

        showErrorDialog(code);

        System.out.println("Google Play Services error");

        FrameLayout fl = (FrameLayout) findViewById(R.id.frameId);
        fl.removeAllViews();
    } else {
        // Create a new global location parameters object
        mLocationRequest = new LocationRequest();

        // Set the update interval
        mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);

        // Use high accuracy
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Set the interval ceiling to one minute
        mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

        bitmapDescriptorBlue = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE);

        blueCircle = BitmapDescriptorFactory
                .fromBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.blue_circle));

        bitmapDescriptorRed = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);

        // Create a new location client, using the enclosing class to handle
        // callbacks
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();

        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapview)).getMap();

        if (map != null) {

            // Set default map center and zoom on Parma
            double lat = 44.7950156;
            double lgt = 10.32547;
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lgt), 12.0f));

            // Adding listeners to the map respectively for zoom level
            // change and onTap event
            map.setOnCameraChangeListener(getCameraChangeListener());
            map.setOnMapClickListener(getOnMapClickListener());

            // Set map type as normal (i.e. not the satellite view)
            map.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL);

            // Hide traffic layer
            map.setTrafficEnabled(false);

            // Enable the 'my-location' layer, which continuously draws an
            // indication of a user's current location and bearing, and
            // displays UI controls that allow the interaction with the
            // location itself
            // map.setMyLocationEnabled(true);

            ml = new HashMap<String, Marker>();

            // Get file manager for config files
            fileManager = FileManager.getFileManager();
            fileManager.createFiles();

            map.setOnMarkerClickListener(this);

        } else {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage("The map cannot be initialized.");
            dialog.setCancelable(true);
            dialog.setPositiveButton(getResources().getString(R.string.ok),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });
            dialog.show();
        }
    }
}

From source file:com.google.android.apps.gutenberg.ScannerActivity.java

private void showCheckinAnimation(Checkin checkin) {
    if (mLastAnimator != null) {
        mLastAnimator.cancel();/*from w  w w  . j  a v  a2 s . c  om*/
    }
    final FrameLayout cover = (FrameLayout) findViewById(R.id.item_cover);
    cover.setVisibility(View.VISIBLE);
    final FrameLayout layer = (FrameLayout) findViewById(R.id.animation_layer);
    final CheckinHolder holder = new CheckinHolder(getLayoutInflater(), layer);
    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.WRAP_CONTENT);
    lp.gravity = Gravity.CENTER_VERTICAL;
    holder.setWillAnimate(true);
    holder.bind(checkin, mImageLoader);
    holder.itemView.setBackgroundColor(Color.rgb(0xf0, 0xf0, 0xf0));
    float elevation = getResources().getDimension(R.dimen.popup_elevation);
    ViewCompat.setTranslationZ(holder.itemView, elevation);
    holder.setLines(false, false);
    layer.addView(holder.itemView, lp);
    // Interpolator for animators
    FastOutSlowInInterpolator interpolator = new FastOutSlowInInterpolator();
    // Pop-up
    Animator popUpAnim = AnimatorInflater.loadAnimator(this, R.animator.pop_up);
    popUpAnim.setTarget(holder.itemView);
    popUpAnim.setInterpolator(interpolator);
    popUpAnim.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            holder.animateCheckin();
        }
    });
    // Wait
    ObjectAnimator waitAnim = new ObjectAnimator();
    waitAnim.setTarget(holder.itemView);
    waitAnim.setPropertyName("translationY");
    waitAnim.setFloatValues(0.f, 0.f);
    waitAnim.setDuration(2000);
    // Slide-down
    ObjectAnimator slideDownAnim = new ObjectAnimator();
    slideDownAnim.setTarget(holder.itemView);
    slideDownAnim.setPropertyName("translationY");
    slideDownAnim.setFloatValues(0.f, calcSlideDistance());
    slideDownAnim.setInterpolator(interpolator);
    // Landing anim
    ObjectAnimator landingAnim = new ObjectAnimator();
    landingAnim.setTarget(holder.itemView);
    landingAnim.setPropertyName("translationZ");
    landingAnim.setFloatValues(elevation, 0.f);
    landingAnim.setInterpolator(interpolator);
    landingAnim.setDuration(500);
    // Play the animators
    AnimatorSet set = new AnimatorSet();
    set.setInterpolator(interpolator);
    set.playSequentially(popUpAnim, waitAnim, slideDownAnim, landingAnim);
    set.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            clean();
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            clean();
        }

        private void clean() {
            mLastAnimator = null;
            layer.removeAllViews();
            cover.setVisibility(View.INVISIBLE);
        }
    });
    mLastAnimator = set;
    set.start();
}

From source file:org.path.episample.android.activities.MainMenuActivity.java

@SuppressLint("InlinedApi")
@Override/*  w  w w. ja v a2s  .  c  o  m*/
protected void onStart() {
    super.onStart();

    // ensure the DbShimService is started
    Intent intent = new Intent(this, DbShimService.class);
    this.startService(intent);

    this.bindService(intent, mConnection,
            Context.BIND_AUTO_CREATE | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0));

    FrameLayout shadow = (FrameLayout) findViewById(R.id.shadow_content);
    View frags = findViewById(R.id.main_content);
    ODKWebView wkt = (ODKWebView) findViewById(R.id.webkit_view);

    if (currentFragment == ScreenList.MAIN_MENU || currentFragment == ScreenList.COLLECT_MODULE
            || currentFragment == ScreenList.SEND_RECEIVE_WIFI_DIRECT_MODULE
            || currentFragment == ScreenList.SEND_RECEIVE_BLUETOOTH_MODULE
            || currentFragment == ScreenList.SELECT_MODULE || currentFragment == ScreenList.NAVIGATE_MODULE
            || currentFragment == ScreenList.RESTORE_MODULE || currentFragment == ScreenList.EDIT_CENSUS_MODULE
            || currentFragment == ScreenList.REMOVE_CENSUS_MODULE
            || currentFragment == ScreenList.INVALIDATE_CENSUS_MODULE
            || currentFragment == ScreenList.FORM_CHOOSER || currentFragment == ScreenList.FORM_DOWNLOADER
            || currentFragment == ScreenList.FORM_DELETER
            || currentFragment == ScreenList.INSTANCE_UPLOADER_TABLE_CHOOSER
            || currentFragment == ScreenList.INSTANCE_UPLOADER
            || currentFragment == ScreenList.INITIALIZATION_DIALOG) {
        shadow.setVisibility(View.GONE);
        shadow.removeAllViews();
        wkt.setVisibility(View.GONE);
        frags.setVisibility(View.VISIBLE);
    } else if (currentFragment == ScreenList.WEBKIT) {
        shadow.setVisibility(View.GONE);
        shadow.removeAllViews();
        wkt.setVisibility(View.VISIBLE);
        wkt.invalidate();
        frags.setVisibility(View.GONE);
    } else if (currentFragment == ScreenList.CUSTOM_VIEW) {
        shadow.setVisibility(View.VISIBLE);
        // shadow.removeAllViews();
        wkt.setVisibility(View.GONE);
        frags.setVisibility(View.GONE);
    }

    FragmentManager mgr = getFragmentManager();
    if (mgr.getBackStackEntryCount() == 0) {
        swapToFragmentView(currentFragment);
    }
}

From source file:com.google.android.gcm.demo.ui.NetworkSchedulerFragment.java

@Override
public void refresh() {
    FrameLayout tasksView = (FrameLayout) getActivity().findViewById(R.id.scheduler_tasks);
    // the view might have been destroyed, in which case we don't do anything
    if (tasksView != null) {
        float density = getActivity().getResources().getDisplayMetrics().density;
        SimpleArrayMap<String, TaskTracker> tasks = mTasks.getTasks();
        LinearLayout tasksList = new LinearLayout(getActivity());
        tasksList.setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < tasks.size(); i++) {
            final TaskTracker task = tasks.valueAt(i);
            CardView taskCard = (CardView) getActivity().getLayoutInflater().inflate(R.layout.widget_task,
                    tasksList, false);/*from   w  w w.ja v  a 2 s . com*/
            ImageView taskIcon = (ImageView) taskCard.findViewById(R.id.task_icon);
            taskIcon.setImageResource(R.drawable.check_circle_grey600);
            taskIcon.setPadding(0, 0, (int) (8 * density), 0);
            TextView taskLabel = (TextView) taskCard.findViewById(R.id.task_title);
            TextView taskParams = (TextView) taskCard.findViewById(R.id.task_params);
            if (task.period == 0) {
                taskLabel.setText(getString(R.string.scheduler_oneoff, task.tag));
                taskParams.setText(getString(R.string.scheduler_oneoff_params, task.windowStartElapsedSecs,
                        task.windowStopElapsedSecs));
            } else {
                taskLabel.setText(getString(R.string.scheduler_periodic, task.tag));
                taskParams.setText(getString(R.string.scheduler_periodic_params, task.period, task.flex));
            }
            TextView taskCreatedAt = (TextView) taskCard.findViewById(R.id.task_created_at);
            taskCreatedAt.setText(getString(R.string.scheduler_secs_ago, DateUtils
                    .formatElapsedTime(SystemClock.elapsedRealtime() / 1000 - task.createdAtElapsedSecs)));
            TextView lastExecuted = (TextView) taskCard.findViewById(R.id.task_last_exec);
            if (task.executionTimes.isEmpty()) {
                lastExecuted.setText(getString(R.string.scheduler_na));
            } else {
                long lastExecTime = task.executionTimes.get(task.executionTimes.size() - 1);
                lastExecuted.setText(getString(R.string.scheduler_secs_ago,
                        DateUtils.formatElapsedTime(SystemClock.elapsedRealtime() / 1000 - lastExecTime)));
            }
            TextView state = (TextView) taskCard.findViewById(R.id.task_state);
            if (task.isCancelled()) {
                state.setText(getString(R.string.scheduler_cancelled));
            } else if (task.isExecuted()) {
                state.setText(getString(R.string.scheduler_executed));
            } else {
                state.setText(getString(R.string.scheduler_pending));
            }
            Button cancel = (Button) taskCard.findViewById(R.id.task_cancel);
            cancel.setVisibility(View.VISIBLE);
            cancel.setText(R.string.scheduler_cancel);
            Button delete = (Button) taskCard.findViewById(R.id.task_delete);
            delete.setVisibility(View.VISIBLE);
            delete.setText(R.string.scheduler_delete);
            if (!task.isCancelled() && (!task.isExecuted() || task.period != 0)) {
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        cancelTask(task.tag);
                        refresh();
                    }
                });
                cancel.setEnabled(true);
                delete.setEnabled(false);
            } else {
                cancel.setEnabled(false);
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mTasks.deleteTask(task.tag);
                        refresh();
                    }
                });
                delete.setEnabled(true);
            }
            tasksList.addView(taskCard);
        }
        tasksView.removeAllViews();
        tasksView.addView(tasksList);
    }
}

From source file:com.stoutner.privacybrowser.MainWebViewActivity.java

@Override
// Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.  The whole premise of Privacy Browser is built around an understanding of these dangers.
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_coordinatorlayout);

    // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
    Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
    setSupportActionBar(supportAppBar);/*  w w w.j a  v  a 2  s .  c o  m*/
    final ActionBar appBar = getSupportActionBar();

    // This is needed to get rid of the Android Studio warning that appBar might be null.
    assert appBar != null;

    // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
    appBar.setCustomView(R.layout.url_bar);
    appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

    // Set the "go" button on the keyboard to load the URL in urlTextBox.
    urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
    urlTextBox.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, load the URL.
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Load the URL into the mainWebView and consume the event.
                try {
                    loadUrlFromTextBox();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                // If the enter key was pressed, consume the event.
                return true;
            } else {
                // If any other key was pressed, do not consume the event.
                return false;
            }
        }
    });

    final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);

    // Implement swipe to refresh
    swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
    swipeToRefresh.setColorSchemeResources(R.color.blue);
    swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mainWebView.reload();
        }
    });

    mainWebView = (WebView) findViewById(R.id.mainWebView);

    // Create the navigation drawer.
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    // The DrawerTitle identifies the drawer in accessibility mode.
    drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));

    // Listen for touches on the navigation menu.
    final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
    assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
    navigationView.setNavigationItemSelectedListener(this);

    // drawerToggle creates the hamburger icon at the start of the AppBar.
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation,
            R.string.close_navigation);

    mainWebView.setWebViewClient(new WebViewClient() {
        // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mainWebView.loadUrl(url);
            return true;
        }

        // Update the URL in urlTextBox when the page starts to load.
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            urlTextBox.setText(url);
        }

        // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
        @Override
        public void onPageFinished(WebView view, String url) {
            formattedUrlString = url;

            // Only update urlTextBox if the user is not typing in it.
            if (!urlTextBox.hasFocus()) {
                urlTextBox.setText(formattedUrlString);
            }
        }
    });

    mainWebView.setWebChromeClient(new WebChromeClient() {
        // Update the progress bar when a page is loading.
        @Override
        public void onProgressChanged(WebView view, int progress) {
            // Make sure that appBar is not null.
            if (appBar != null) {
                ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
                progressBar.setProgress(progress);
                if (progress < 100) {
                    progressBar.setVisibility(View.VISIBLE);
                } else {
                    progressBar.setVisibility(View.GONE);

                    //Stop the SwipeToRefresh indicator if it is running
                    swipeToRefresh.setRefreshing(false);
                }
            }
        }

        // Set the favorite icon when it changes.
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
            favoriteIcon = icon;

            // Place the favorite icon in the appBar if it is not null.
            if (appBar != null) {
                ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView()
                        .findViewById(R.id.favoriteIcon);
                imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
            }
        }

        // Enter full screen video
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (appBar != null) {
                appBar.hide();
            }

            // Show the fullScreenVideoFrameLayout.
            assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
            fullScreenVideoFrameLayout.addView(view);
            fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);

            // Hide the mainWebView.
            mainWebView.setVisibility(View.GONE);

            // Hide the ad if this is the free flavor.
            BannerAd.hideAd(adView);

            /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
             * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
             * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
             */

            // Set the one flag supported by API >= 14.
            view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

            // Set the two flags that are supported by API >= 16.
            if (Build.VERSION.SDK_INT >= 16) {
                view.setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
            }

            // Set all three flags that are supported by API >= 19.
            if (Build.VERSION.SDK_INT >= 19) {
                view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            }
        }

        // Exit full screen video
        public void onHideCustomView() {
            if (appBar != null) {
                appBar.show();
            }

            // Show the mainWebView.
            mainWebView.setVisibility(View.VISIBLE);

            // Show the ad if this is the free flavor.
            BannerAd.showAd(adView);

            // Hide the fullScreenVideoFrameLayout.
            assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
            fullScreenVideoFrameLayout.removeAllViews();
            fullScreenVideoFrameLayout.setVisibility(View.GONE);
        }
    });

    // Allow the downloading of files.
    mainWebView.setDownloadListener(new DownloadListener() {
        // Launch the Android download manager when a link leads to a download.
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));

            // Add the URL as the description for the download.
            requestUri.setDescription(url);

            // Show the download notification after the download is completed.
            requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // Initiate the download and display a Snackbar.
            downloadManager.enqueue(requestUri);
            Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT)
                    .show();
        }
    });

    // Allow pinch to zoom.
    mainWebView.getSettings().setBuiltInZoomControls(true);

    // Hide zoom controls.
    mainWebView.getSettings().setDisplayZoomControls(false);

    // Initialize the default preference values the first time the program is run.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Get the shared preference values.
    SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Set JavaScript initial status.  The default value is false.
    javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
    mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);

    // Initialize cookieManager.
    cookieManager = CookieManager.getInstance();

    // Set cookies initial status.  The default value is false.
    firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
    cookieManager.setAcceptCookie(firstPartyCookiesEnabled);

    // Set third-party cookies initial status if API >= 21.  The default value is false.
    if (Build.VERSION.SDK_INT >= 21) {
        thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
        cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
    }

    // Set DOM storage initial status.  The default value is false.
    domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
    mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);

    // Set the user agent initial status.
    String userAgentString = savedPreferences.getString("user_agent", "Default user agent");
    switch (userAgentString) {
    case "Default user agent":
        // Do nothing.
        break;

    case "Custom user agent":
        // Set the custom user agent on mainWebView,  The default is "PrivacyBrowser/1.0".
        mainWebView.getSettings()
                .setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
        break;

    default:
        // Set the selected user agent on mainWebView.  The default is "PrivacyBrowser/1.0".
        mainWebView.getSettings()
                .setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
        break;
    }

    // Set the initial string for JavaScript disabled search.
    if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=")
            .equals("Custom URL")) {
        // Get the custom URL string.  The default is "".
        javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
    } else {
        // Use the string from javascript_disabled_search.
        javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search",
                "https://duckduckgo.com/html/?q=");
    }

    // Set the initial string for JavaScript enabled search.
    if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=")
            .equals("Custom URL")) {
        // Get the custom URL string.  The default is "".
        javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
    } else {
        // Use the string from javascript_enabled_search.
        javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search",
                "https://duckduckgo.com/?q=");
    }

    // Set homepage initial status.  The default value is "https://www.duckduckgo.com".
    homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");

    // Set swipe to refresh initial status.  The default is true.
    swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
    swipeToRefresh.setEnabled(swipeToRefreshEnabled);

    // Get the intent information that started the app.
    final Intent intent = getIntent();

    if (intent.getData() != null) {
        // Get the intent data and convert it to a string.
        final Uri intentUriData = intent.getData();
        formattedUrlString = intentUriData.toString();
    }

    // If formattedUrlString is null assign the homepage to it.
    if (formattedUrlString == null) {
        formattedUrlString = homepage;
    }

    // Load the initial website.
    mainWebView.loadUrl(formattedUrlString);

    // Initialize AdView for the free flavor and request an ad.  If this is not the free flavor BannerAd.requestAd() does nothing.
    adView = findViewById(R.id.adView);
    BannerAd.requestAd(adView);
}