所以我检查了此codelab by Google以在Android中创建自定义视图RatioImageView
。它只是扩展ImageView并根据设备的视口的宽高比覆盖OnMeasure()
方法。相同的代码是:
class RatioImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
): ImageView(context, attrs, defStyleAttr) {
private val VP_HEIGHT = Resources.getSystem().displayMetrics.heightPixels
private val VP_WIDTH = Resources.getSystem().displayMetrics.widthPixels
private val HWR: Float = VP_HEIGHT.toFloat()/VP_WIDTH.toFloat() //height to width ratio
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),(MeasureSpec.getSize(widthMeasureSpec)*HWR).toInt())
}
}
然后我在ListItem视图中将其用作:
<?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">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="0dp">
<com.example.myapp.RatioImageView
android:id="@+id/target"
android:layout_width="match_parent"
android:layout_height="0dp"
android:contentDescription="image holder"
android:scaleType="centerCrop"
android:background="#757575"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="9:16" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
然后在适配器中,我正在使用DataBinding
来更新具有如下内容的视图:
override fun onBindViewHolder(holder: HomeItemHolder, position: Int) {
holder.binding.apply {
//loadImage() is an extension function added to ImageView class
target.loadImage(UiUtil.getCustomUrl(photos[position].urls.fullImage, height, width))
root.setOnClickListener {
handleClick(position)
}
}
}
在构建期间,它显示以下错误:
Cannot access class 'RatioImageView'. Check your module classpath for missing or conflicting dependencies
即在OnBindViewHolder()
中写入target.loadImage(...)
的行此外,如果我不将DataBinding用于根布局,则可以正常工作。
所以问题是,需要在RatioImageView
中添加什么?为了使其与DataBinding一起使用,考虑到这里我不需要将XML布局与View类关联。
这里是onCreateViewHolder()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeItemHolder {
return HomeItemHolder(ItemPhotoListLayoutBinding.inflate(LayoutInflater.from(parent.context)))
}
下面是ViewHolder
类:
inner class HomeItemHolder (val binding: ItemPhotoListLayoutBinding):
RecyclerView.ViewHolder(binding.root) {
}
您试图将数据绑定到xml中的哪个属性?也许您想将图像绑定到android:src
属性?在这种情况下:
<variable name="image" type="Drawable"/>
标签内添加<data>
src
,例如android:id="@{image}"
尝试以下操作:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.binding.apply {
this.image = loadImage(UiUtil.getCustomUrl(photos[position].urls.fullImage, height, width))
root.setOnClickListener {
handleClick(position)
}
}