所以我检查了谷歌的这个代码实验室来创建一个自定义视图RatioImageView。OnMeasure()它只是扩展 ImageView 并根据设备的视口的纵横比覆盖该方法。相同的代码是:
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)
}
}
}
在构建过程中,它显示以下错误:
无法访问类“RatioImageView”。检查您的模块类路径是否存在缺失或冲突的依赖项
即在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) {
}
如果我的代码在这里遗漏了一些东西,这里也是回购:https ://github.com/prafullmishra/CustomImageView