BindingAdapter(kotlin自定义数据绑定)

app module的build.gradle文件添加

apply plugin: 'kotlin-kapt'
  • ImageView
@BindingAdapter("imageFromUrl")
fun bindImageFromUrl(view: ImageView, imageUrl: String?) {
    if (!imageUrl.isNullOrEmpty()) {
        Glide.with(view.context)
                .load(imageUrl)
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(view)
    }
}

 
  • View Gone
@BindingAdapter("isGone")
fun bindIsGone(view: View, isGone: Boolean) {
    view.visibility = if (isGone) {
        View.GONE
    } else {
        View.VISIBLE
    }
}

@BindingAdapter("isGone")
fun bindIsGone(view: FloatingActionButton, isGone: Boolean?) {
    if (isGone == null || isGone) {
        view.hide()
    } else {
        view.show()
    }
}

//xml使用app:isGone="@{!hasPlantings}"
//UI赋值 binding.hasPlantings = !result.isNullOrEmpty()
  • TextView
@BindingAdapter("renderHtml")
fun bindRenderHtml(view: TextView, description: String?) {
    if (description != null) {
        view.text = HtmlCompat.fromHtml(description, FROM_HTML_MODE_COMPACT)
        view.movementMethod = LinkMovementMethod.getInstance()
    } else {
        view.text = ""
    }
}

                
   @BindingAdapter(value = ["licenseNumber","vinLast4"])
    @JvmStatic
   fun bindText(textView: TextView,licenseNumber: String,vinLast4:String){
       if (licenseNumber==""){
           textView.text = vinLast4
       }else{
           textView.text = licenseNumber
       }
   }
   
   
                       

你可能感兴趣的:(Kotlin)