原文: https://blog.csdn.net/qq_42420293/article/details/120406041
自定义BindingAdapter
1、ImageView
1.1、给iv绑定img的url
当img的url数据改变, 自动更新img的图片
@BindingAdapter("imageUrl")
fun bindImage(imgView: ImageView, imgUrl: String?) {
imgUrl?.let {
val imgUri = imgUrl.toUri().buildUpon().scheme("https").build()
Glide.with(imgView.context)
.load(imgUri)
.apply(RequestOptions()
.placeholder(R.drawable.loading_animation)
.error(R.drawable.ic_broken_image))
.into(imgView)
}
}
1.2、给iv绑定当前状态
根据iv的状态设置iv显示的资源图片及可见性
@BindingAdapter("marsApiStatus")
fun bindStatus(statusImageView: ImageView, status: MarsApiStatus?) {
when (status) {
MarsApiStatus.LOADING -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.loading_animation)
}
MarsApiStatus.ERROR -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.ic_connection_error)
}
MarsApiStatus.DONE -> {
statusImageView.visibility = View.GONE
}
}
}
2、RecyclerView
2.1、给rv绑定data
当rv列表数据改变,rv自动更新数据列表
@BindingAdapter("listData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<MarsProperty>?) {
val adapter = recyclerView.adapter as PhotoGridAdapter
adapter.submitList(data)
}
3、TextView
3.1、将接口返回的带html标签的数据使用html格式排版显示
@BindingAdapter("bind_setTextWithHTML")
fun bindText(textView: TextView, text: String?){
text?.let {
textView.setText(Html.fromHtml(text))
}
}
4、WebView
4.1、给webView绑定url
当url改变,自动加载webview显示的网页
@BindingAdapter("bind_webviewUrl")
fun binWebViewUrl(webView: WebView, webUrl: String?){
webUrl?.let {
webView.loadUrl(webUrl)
}
}