效果图
背景
之前写过的文章——WebView+Fragment+ViewPager构建浏览器多标签页 虽然实现了多标签页的功能,但是有个弊端就是随着创建的标签页数量增加,viewpager的滑动会越来越卡。之前一直没有时间优化,最近尝试着优化了一下,对Dainty浏览器的多标签页功能抽取出来,进行改造。
思路
WebTabManager用于管理tab页面对象
class WebTabManager private constructor(){
private object Holder{
val instance = WebTabManager()
}
companion object Instance {
var increaseKey = 0
@JvmStatic
fun getInstance(): WebTabManager{
return Holder.instance
}
}
private val cacheWebTab = LinkedList<WebBean>()
fun divideAllWebView(){
LogUtil.d("divideAllWebView: ${cacheWebTab.size}")
for (wb in cacheWebTab){
wb.webView.parent?.let {
(it as ViewGroup).removeAllViews()
}
}
}
fun getCacheWebTab(): List<WebBean>{
return cacheWebTab
}
fun addNewTab(): WebBean {
val webView = CommonWebView(MutableContextWrapper(Dainty2Application.app))
val wb = WebBean(increaseKey++, webView, "首页", ContextCompat.getDrawable(Dainty2Application.app, R.drawable.web_tab_icon_home), ContextCompat.getDrawable(Dainty2Application.app, R.drawable.ic_launcher_foreground))
cacheWebTab.add(wb)
return wb
}
fun joinWebTabToLast(key: Int){
for (wb in cacheWebTab){
if (wb.id == key){
cacheWebTab.remove(wb)
cacheWebTab.addLast(wb)
break
}
}
}
fun updateLastTabTitle(tabTitle: String){
val wb = cacheWebTab.last
wb.tabTitle = tabTitle
}
fun updateLastTabIcon(tabIcon: Drawable){
val wb = cacheWebTab.last
wb.tabIcon = tabIcon
}
}
tab页面对象,保存了webview对象,网页icon和标题,网页截图
data class WebBean(val id: Int, val webView: CommonWebView, var tabTitle: String,
var tabIcon: Drawable?, var picture: Drawable?)
用于获取网页截图
fun catchWebView(context: Context){
val capture = WebTabManager.getInstance().getCacheWebTab().last().webView
capture.isDrawingCacheEnabled = true
val bitmap = capture.drawingCache
WebTabManager.getInstance().getCacheWebTab().last().picture = BitmapDrawable(context.resources, bitmap).current
}
具体可参考:Dainty2
|