Android ImageView自定义BindingAdapter

这是一个很适用的小技巧
以下代码都是来自开源项目PokemonGo

  • 配置build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt' //这个必须加,不然报错
android {
    
    
    ...
    // 这些都需要配置上
    buildFeatures {
    
    
        dataBinding = true
    }
    compileOptions {
    
    
    	sourceCompatibility JavaVersion.VERSION_1_8
    	targetCompatibility JavaVersion.VERSION_1_8
	}
	kotlinOptions {
    
    
    	jvmTarget = JavaVersion.VERSION_1_8.toString()
	}
}
  • 自定义BindingAdapter
@BindingAdapter("bindingAvator")
fun bindingAvator(imageView: ImageView, url: String) {
    
    
    imageView.load(url) {
    
    
        crossfade(true)
        placeholder(R.mipmap.ic_launcher_round)
    }
}
@BindingAdapter("bindSmallImage")
fun bindingSmallImage(imageView: ImageView, url: String) {
    
    
    imageView.load(url) {
    
    
        crossfade(true)
        placeholder(R.mipmap.ic_launcher_round)
        size(280,280)
    }
}

使用用coil加载图片

implementation("io.coil-kt:coil:1.0.0")
  • 具体使用
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="album"
            type="com.hi.dhl.pokemon.model.PokemonInfoModel.AlbumModel" />
    </data>
    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/avator"
        android:layout_width="@dimen/dp_80"
        android:layout_height="@dimen/dp_80"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:src="@mipmap/ic_launcher_round" /> 
        app:bindSmallImage="@{album.url}" />
</layout>
  • 设置url
// 委托,生成ViewDataBinding
inline fun <reified T : ViewDataBinding> viewHolderBinding(view: View): Lazy<T> =
lazy {
    
    
    requireNotNull(DataBindingUtil.bind<T>(view)) {
    
     "cannot find the matched layout." }
}
// 使用委托生成ViewDataBinding对象
private val mBinding: RecycleItemAlbumBinding by viewHolderBinding(view)
// 为bindSmallImage属性设置url
mBinding.apply {
    
    
    album = data
    executePendingBindings()
}

猜你喜欢

转载自blog.csdn.net/MoLiao2046/article/details/109815475