implementation ‘com.google.code.gson:gson:2.8.6’
② 添加 Javapoet 常用 api
annotationProcessor ‘com.google.code.gson:gson:2.8.6’
//Kotlin 需要kapt支持
apply plugin: 'kotlin-android’apply
plugin: ‘kotlin-android-extensions’
//kapt插件、会有很多问题、博客地址:https://www.jianshu.com/p/b58d733bc54eapply
plugin: ‘kotlin-kapt’
③ 使用 @AutoService 注解
//第一步 创建下沉接口
interface IWebViewService {
fun startWebActivity(context: Context, title: String, url: String)
fun startWebFragment(url: String): Fragment
fun starLocalTestHtml(context: Context)
}// 第二步 实现接口
@AutoService(IWebViewService::class)
class WebViewServiceImpl : IWebViewService {
override fun startWebActivity(context: Context, title: String, url: String) {
WebActivity.create(context, title, url)
}
override fun startWebFragment(url: String): Fragment {
return WebFragment.create(url)
}
override fun starLocalTestHtml(context: Context) {
WebActivity.createHtml(context)
}
}// 第三步 查找实例、进行通信
binding.starWebActivity.setOnClickListener {
// AutoService工具类找实现
AutoService.load(IWebViewService::class.java)?.apply {
starLocalTestHtml(this@AccountActivity)
}
}
object AutoService {
fun load(clazz: Class): S? {
val service = ServiceLoader.load(clazz).iterator()
try {
if (service.hasNext()) {
return service.next()
}
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
}
以上就完成了 组件化的初步构建,结构如下图
3. WebView 组件封装
1).WebView 的组成部分
WebView由四个部分组成的: