在Kotlin中使用数据绑定将图像url设置为图像视图时,我遇到了一些问题。
我的数据类如下:
data class ItemInfo(val img:String,val fname:String,val lname:String){
companion object {
@BindingAdapter("img")
@JvmStatic
fun loadImage(imageView: ImageView, url: String) {
if (url != "") {
// Picasso.with(imageView.getContext()).load(url).resize(200, 200).into(imageView).
Picasso.get().load(url).into(imageView)
}
}
}
}
我的布局如下:
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<data>
<variable name="item"
type="com.example.jetpackmvvmdemos.DataBindingAdapter.models.ItemInfo">
</variable>
</data>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/imageView"
android:scaleType="fitXY"
app:img="@{item.img}"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:text="@{item.fname}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView3"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/imageView"/>
<TextView
android:text="@{item.lname}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView4"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/textView3"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</layout>
视图模型:
class EmpViewModel:ViewModel() {
var empInfoList:MutableList<ItemInfo>
init {
empInfoList = mutableListOf<ItemInfo>()
empInfoList.add(ItemInfo("https://via.placeholder.com/50x50.png?text=1","ABC","DEF"))
empInfoList.add(ItemInfo("https://via.placeholder.com/50x50.png?text=2","GHI","JKL"))
empInfoList.add(ItemInfo("https://via.placeholder.com/50x50.png?text=3","MNO","PQR"))
empInfoList.add(ItemInfo("https://via.placeholder.com/50x50.png?text=4","STU","VWX"))
}
}
class ListInfoAdapter(var context: Context) : RecyclerView.Adapter<ListInfoAdapter.ViewHolder>() {
private var list: List<ItemInfo> = emptyList<ItemInfo>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding: ListItemBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.list_item, parent, false)
return ListInfoAdapter.ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Log.d("ADapter", "Info:::" + list.get(position).body)
holder.bind(list.get(position))
}
fun setAdapterList(list: List<ItemInfo>) {
this.list = list
notifyDataSetChanged()
}
override fun getItemCount(): Int = list.size
class ViewHolder(val binding: ListItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(data: Any) {
binding.setVariable(BR.item, data) // BR - generated class; BR.item - 'item' is variable name declared in layout
binding.executePendingBindings()
}
}
}
碎片:
class DataBindingListFragment: Fragment() {
var fragmentView: View? = null
private var listAdapter: ListInfoAdapter? = null
private var listLayoutBinding: com.example.jetpackmvvmdemos.databinding.EmpInfoListFragmentLayoutBinding? = null
// lateinit var empViewModel: EmpViewModel
val empViewModel: EmpViewModel by lazy { ViewModelProviders.of(this).get(EmpViewModel::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
listLayoutBinding = DataBindingUtil.inflate(inflater, R.layout.emp_info_list_fragment_layout, container, false)
fragmentView = listLayoutBinding?.root
initAdapter()
setAdapter()
fetchEmpInfo()
return fragmentView
}
fun fetchEmpInfo() {
listAdapter?.setAdapterList(empViewModel.empInfoList)
}
fun setAdapter(){
fragmentView?.emprecyclerView?.apply {
layoutManager = LinearLayoutManager(activity)
addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
adapter = listAdapter
}
}
private fun initAdapter() {
listAdapter = ListInfoAdapter(this@DataBindingListFragment.requireActivity())
}
}
Build.Gradle(应用程序级)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.jetpackmvvmdemos"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}
dependencies {
ext.compiler_version = '3.3.1'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
implementation 'androidx.core:core-ktx:1.2.0-rc01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
kapt "com.android.databinding:compiler:$compiler_version"
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
def lifecycle_version = "2.1.0"
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation 'com.squareup.picasso:picasso:2.71828'
}
kapt {
generateStubs = true
}