“This is the 17th day of my participation in the First Challenge 2022.

Import Tencent X5WebView why not system webview

X5 kernel has the following obvious advantages over system WebView:

  • Fast speed: compared with the system webview webpage opening speed of 30+%;
  • Save traffic: use cloud optimization technology to save traffic by 20+%;
  • Safer: Security issues can be fixed within 24 hours;
  • More stable: After hundreds of millions of users, the CRASH rate is lower than 0.15%;
  • Good compatibility: no fragmentation of the system kernel, less compatibility problems;
  • Excellent experience: support night mode, suitable screen layout, font Settings and other browsing enhancements;
  • Full features: more complete support on Html5 and ES6;
  • More powerful: integrated powerful video player, support video format far more than the system Webview;
  • Video and file formats are supported by the X5 kernel more than the system kernel
  • Anti-hijacking is one of the key features of the X5 kernel

About TBS

Tencent Browsing service is committed to optimize the mobile webview experience of the entire solution. The solution consists of SDK, mobile QQ browser X5 kernel and X5 cloud service to solve all the problems in the use of mobile webView and optimize the user’s browsing experience. At the same time, Tencent will continue to provide follow-up updates and optimizations to provide developers with the latest and best functions and services.

Import X5Webview

Import dependence

api 'com.tencent.tbs:tbssdk:44153'
Copy the code

The difference between Implementation and API

Implementation is like praivte; module references to implementation apply only to themselves and are not passed. The API is similar to “public”. Other modules can also reference resources in this module by dependency.

Add permissions


      
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        .
        <service
            android:name="com.tencent.smtt.export.external.DexClassLoaderProviderService"
            android:label="dexopt"
            android:process=":dexopt" >
        </service>
    </application>

</manifest>
Copy the code

See x5 Fast Access (tencent.com)

Method of use

fragment_web.xml


      
<layout
    xmlns:android="http://schemas.android.com/apk/res/android">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.tencent.smtt.sdk.WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Copy the code

Create a new WebFragment class

Use argument to pass link arguments

companion object {
    private const val LOAD_URL = "load_url"
    
    fun load(url: String): WebFragment {
        return WebFragment().apply {
            arguments = bundleOf(LOAD_URL to url)

        }
    }
}
Copy the code

Receive the parameters and load the table with loadUrl

arguments? .let { args -> args.getString(LOAD_URL)? .let { mBinding.webView.loadUrl(it) } }Copy the code

Configuration WebSettings

val webSettings: WebSettings = mBinding.webView.settings
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { // Solve the problem of not displaying images in web pages
    webSettings.mixedContentMode = WebSettings.LOAD_DEFAULT
}
webSettings.javaScriptEnabled = true JS / / support
webSettings.domStorageEnabled = true // Support DOM Storage
webSettings.defaultTextEncodingName = "utf-8" // Set the encoding format
webSettings.pluginState = WebSettings.PluginState.ON// Support plugins
webSettings.loadsImagesAutomatically = true // Support automatic loading of images
webSettings.setSupportZoom(true) // Supports scaling and defaults to true. That's the premise of the following one.
webSettings.builtInZoomControls = true // Set the built-in zoom control. If false, the WebView is not scalable
webSettings.displayZoomControls = false // Hide the native zoom control
webSettings.databaseEnabled = true // The database storage API is available
webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN //WebView layout algorithm
webSettings.cacheMode =
    WebSettings.LOAD_CACHE_ELSE_NETWORK // Set the cache to use the data in the cache as long as it is locally available, regardless of whether it is stale or no-cache. It is obtained from the network only when there is no local cache
webSettings.allowFileAccess = true // Set access to files
webSettings.javaScriptCanOpenWindowsAutomatically = true // Support to open new Windows through JS

// Set up the adaptive screen
webSettings.useWideViewPort = true // Resize the image to fit the WebView
webSettings.loadWithOverviewMode = true // Zoom to the size of the screen
Copy the code

Then enter the search link on the home page HomeFragment to jump to WebFragment

Fragment_home.xml search box +FrameLayout


      
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <EditText
            android:id="@+id/ed_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="166dp"
            android:layout_marginEnd="16dp"
            android:padding="12dp"
            android:imeOptions="actionSearch"
            android:background="@drawable/gray_rounded_shape"
            android:drawableLeft="@drawable/ic_search_gray_24dp"
            app:layout_constraintTop_toTopOf="parent" />

        <FrameLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Copy the code

The search button at the bottom right of the soft keyboard

android:imeOptions="actionSearch"
Copy the code

HomeFragment

Listen search button

mBinding.edSearch.setOnEditorActionListener(OnEditorActionListener { textView, actionId, keyEvent ->
    if((actionId == EditorInfo.IME_ACTION_UNSPECIFIED || actionId == EditorInfo.IME_ACTION_SEARCH) && keyEvent ! =null) {
        // Click the search action to do
        toWebView()
        return@OnEditorActionListener true
    }
    false
})
Copy the code

Using childFragmentManager to manage WebFragments also involves multiple Windows

fun toWebView(a){
    childFragmentManager.commit {
        addToBackStack("HomeFragment")
        var search = "${mBinding.edSearch.text}"
        val baiduUrl = "https://www.baidu.com/s?wd=$search"
        var webFragment = WebFragment.load(baiduUrl)
        add(R.id.content, webFragment)// Replace cannot be used, otherwise it will be rebuilt each time you return}}Copy the code

Listen for the back key to return to the desktop

requireActivity().onBackPressedDispatcher.addCallback(this.object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed(a) {
        isEnabled = childFragmentManager.backStackEntryCount > 0
        if (isEnabled){
            childFragmentManager.popBackStackImmediate()
          
        }
        else requireActivity().finish()
    }
})
Copy the code