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)
}
}
<ImageView
android:id="@+id/detail_image"
android:layout_width="match_parent"
android:layout_height="@dimen/plant_detail_app_bar_height"
android:contentDescription="@string/plant_detail_image_content_description"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:imageFromUrl="@{viewModel.plant.imageUrl}"
app:layout_collapseMode="parallax" />
- 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 = ""
}
}
<TextView
android:id="@+id/plant_description"
style="?android:attr/textAppearanceMedium"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/margin_small"
android:layout_marginTop="@dimen/margin_small"
android:layout_marginEnd="@dimen/margin_small"
android:textIsSelectable="true"
android:minHeight="@dimen/plant_description_min_height"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/plant_watering"
app:renderHtml="@{viewModel.plant.description}"
tools:text="Details about the plant" />
@BindingAdapter(value = ["licenseNumber","vinLast4"])
@JvmStatic
fun bindText(textView: TextView,licenseNumber: String,vinLast4:String){
if (licenseNumber==""){
textView.text = vinLast4
}else{
textView.text = licenseNumber
}
}
<TextView
android:id="@+id/tv_item_name"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:textSize="14sp"
android:textColor="#ff696d77"
android:gravity="center_vertical"
app:licenseNumber="@{myData.licenseNumber}"
app:vinLast4="@{myData.vinLast4}"/>