需求:我们需要做一个h5页面,并且可以现实加载更多,并且头部我们想要加一个视频播放器,因为h5不够丝滑。
话不多说咱们直接上代码
Xml布局:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><WebViewandroid:id="@+id/vView"android:layout_width="match_parent"android:layout_height="match_parent" /></androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {var url1: String ="https://www.baidu.com/"override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)var mView = findViewById<WebView>(R.id.vView)var topRelativeLayout = RelativeLayout(this)val topLp = RelativeLayout.LayoutParams(ScreenUtils.getScreenWidth(this), 400)topRelativeLayout.layoutParams = topLpval lp = RelativeLayout.LayoutParams(ScreenUtils.getScreenWidth(this) - 30, 360)lp.leftMargin = ScreenUtils.dip2px(this, 15f)lp.rightMargin = ScreenUtils.dip2px(this, 15f)lp.topMargin = ScreenUtils.dip2px(this, 20f)lp.addRule(RelativeLayout.CENTER_HORIZONTAL)topRelativeLayout.addView(getViewTop(), lp)mView.addView(topRelativeLayout)val wSet: WebSettings = mView.settingswSet.javaScriptEnabled = true//设置自适应屏幕wSet.useWideViewPort = true //将图片调整到适合webview的大小wSet.loadWithOverviewMode = false // 缩放至屏幕的大小mView.loadUrl(url1)mView.webViewClient = object : WebViewClient() {// 链接跳转都会走这个方法override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {Log.d("MainActivity", "Url:$url")view.loadUrl(url) // 强制在当前 WebView 中加载 urlreturn true}}}private fun getViewTop(): View? {return LayoutInflater.from(this).inflate(R.layout.view_top, null)}
}