Android provides the WebView component, which is itself a browser implementation.

The following methods of WebView are mainly used in this example:

  • Void loadUrl(String URL) Loads the web page corresponding to the specified URL
  • Void goBack () back
  • Void goForward () to move forward
  • According to the Boolean canGoBack ()The historical recordCheck whether the rollback can be performed
  • According to the Boolean canGoForward ()The historical recordDetermine if you can move forward
  • WebSettings getSettings() gets the WebSettings object that controls the WebView (call itsetJavaScriptEnabledMethods makeWebViewsupportJavaScript)
  • Void setWebViewClient(WebViewClient client) The WebViewClient is responsible for handling WebView notifications and requests, such as page loading and completion, resource loading, url opening, etc
  • Void setWebChromeClient(WebChromeClient client) WebChromeClient mainly assists WebView to process Javascript dialog boxes, website ICONS, website titles, and loading progress

Overview of browser features:

  1. The default is when you first open the appbaiduSet to the home page, through the bottomThe home pageButton to jump to the home page, or by long press the pop-up dialog box to modify the home page
  2. The home pageThe URL address is usedSharedPreferencesave
  3. At the bottom of the fourImageButtonFrom doing to the rightThe home page The refresh The fallback forward
  4. At the top of theActionBarwithvoid setCustomView(View)Added a custom forEnter urlThe input box and aGo to theButton,Go to theButtons are invisible and unavailable by default when clickedEnter urltheEditTextIt will be displayed and available.
  5. Used to display page loading progressProgressBar

screenshots

Code section

  • This method is called each time a web page is opened, and is controlled hereActionBarWithin theEdittextAccording toLoading in...
 mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mShowTitle.setText("Loading..."); }... }Copy the code
  • overwriteshouldOverrideUrlLoadingAnd returntrueOtherwise, the WebView will default to calling the system’s browser or a third-party browser instead of using the current activityWebView
mWebView.setWebViewClient(new WebViewClient() {
			...
			@Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true; }... }Copy the code
  • Callback when page loading progress changesonProgressChangedMethod, which is updated here to show progressProgressBar. Pay attention tonewProgressThe values are 0 to 100, so theProgressBarThe maximum value is set to 100.
  • onReceivedTitleReturns the title of the currently loaded page to display on the EditText within the actionBar.
mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                mProgressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    mProgressBar.postDelayed(() -> mProgressBar.setProgress(0), 2000); }}@Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title); currentUrlTitle = title; mShowTitle.setText(currentUrlTitle); }});Copy the code
  • Listening for physical KeysreturnClick the event ifWebViewtheThe historical recordWhen there is a previous page of related recordsvoid goBack()methods
@Override
    public void onBackPressed(a) {
        if (mWebView.canGoBack())
            mWebView.goBack();
        else finish();
    }
Copy the code
  • Check whether you are currently in the state of entering the URL (EditText on the actionBar). If yes, call this method to indicate the end of the inputGo to theButton disappearance is not enabled by 2EditTextControl loses focus, otherwise the cursor will always show, the effect is not good
private void finishEdit(a) {
        if (isEditFocus) {
            isEditFocus = false;
            mShowTitle.clearFocus();

            Animation animation = AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.fade_out);
            animation.setFillAfter(true);
            mLoadUrl.startAnimation(animation);
            mLoadUrl.setEnabled(false); mShowTitle.setText(currentUrlTitle); }}Copy the code

This method is invoked in three places: 1. When the user is inputting the URL, he/she will transfer his/her attention to the WebView and touch the WebView. At this time, the user will judge whether the soft keyboard is displayed, close the soft keyboard when it is displayed, and then make the input box lose focus and hide the go button

 mWebView.setOnTouchListener((View view, MotionEvent event) -> {
       if (event.getAction() == MotionEvent.ACTION_DOWN) {
           finishEdit();
           InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
           if (imm.isActive())
               imm.hideSoftInputFromWindow(mShowTitle.getWindowToken(),0);

       }
       return false;
   });

Copy the code

Void onBackPressed() will not be called because the soft keyboard is being displayed. Boolean dispatchKeyEvent(KeyEvent event) will be called to block the button click event. Turn off the soft keyboard while the input box is out of focus and hide the go button.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
            finishEdit();
        return super.dispatchKeyEvent(event);
    }
Copy the code

3. After clicking the “Go to” button 3.1 in actionBar, it is necessary to judge whether the input is correct, and then whether the input URL is new (different from that of the web page currently being displayed). If so, let the WebView load the web page. Close the soft keyboard while it is displayed and then unfocus the input box and hide the go button

The following code contains click events for all buttons, each of which has an Android attribute added to the XML :onClick=”onClick”

 public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_goBack:
                if (mWebView.canGoBack())
                    mWebView.goBack();
                break;
            case R.id.main_goForward:
                if (mWebView.canGoForward())
                    mWebView.goForward();
                break;
            case R.id.main_refresh:
                mWebView.loadUrl(currentUrl);
                break;
            case R.id.actionBar_goto:
                String url = mShowTitle.getText().toString() == "" ? null : mShowTitle.getText().toString().equals(currentUrl) ? null : mShowTitle.getText().toString();
                if(url ! =null)
                    mWebView.loadUrl(url);

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive())
                    imm.hideSoftInputFromWindow(mShowTitle.getWindowToken(),0);

                finishEdit();
                break;
            case R.id.main_home:
                if(! currentUrl.equals(homeUrl)) mWebView.loadUrl(homeUrl);break; }}Copy the code

What to look out for:

  • Use in stylecolorControlHighlightProperty to change the color of the default button click ripple effect like this:
<item name="colorControlHighlight">@color/colorPrimary</item>
Copy the code
  • In the XML property of the button
style=`"@style/Base.Widget.AppCompat.Button.Borderless.Colored"
Copy the code

The effect of button clicks is not restricted by layout boundaries. Other views that are not clickable by default (EditText, TextView, etc.) should also be added:

android:clickable="true"
Copy the code
  • The ICONS used can be downloaded here: Material ICONS – Material Design
  • callActionBarthesetCustomViewMethod is called firstsetDisplayShowCustomEnabledMethod collocate to true.
  • Modify the home page using the dialog box:
 AlertDialog.Builder builder
	 .setTitle("Modify home page")
     .setNegativeButton("Cancel", (DialogInterface dialog, int which) -> dialog.dismiss())
Copy the code

Here it is use new DialogInterface. An OnClickListener () {… }, Lambda, build. Gradle, build.

android {
    ...
        jackOptions {
            enabled true}... }... CompileOptions {targetCompatibility 1.8sourceCompatibility 1.8}... }Copy the code