Android WebView 实现折叠功能

WebView 实现折叠,查看更多
实现代码

private fun init() {
//... 省略更多
       webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                launchUI {
                    delay(300)
                    toggleHeight()
                }
            }
        }

        binding.tvExpand.click {
            binding.webView.layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            binding.tvExpand.isVisible = false
            disabledScroll(true)
        }
//... 省略更多
}

    private fun toggleHeight() {
        val height = webView.height
        val maxHeight = dp2px(320f)
        if (height > maxHeight) {
            val lp: LinearLayout.LayoutParams =
                webView.layoutParams as LinearLayout.LayoutParams
            lp.height = maxHeight
            webView.layoutParams = lp
            disabledScroll(false)
            tvExpand.isVisible = true  // tvExpand 是【查看更多】按钮
        } else {
            tvExpand.isVisible = false
        }
    }

    private fun disabledScroll(disable: Boolean = false) {
        webView.isVerticalScrollBarEnabled = disable
        webView.isHorizontalScrollBarEnabled = disable
        webView.isScrollContainer = disable
        if (!disable) {
            webView.setOnTouchListener { p0, p1 -> p1?.action == MotionEvent.ACTION_MOVE }
        } else {
            webView.setOnTouchListener(null)
        }
    }

页面布局 xml

... // 省略更多


            

                

                

            
        
... // 省略更多

你可能感兴趣的:(Android WebView 实现折叠功能)