Итак, я проверил эту кодовую метку от Google для создания пользовательского представления RatioImageView
в Android. Он просто расширяет 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
, т.е. для строки, в которой target.loadImage(...)
записано в OnBindViewHolder ( )
Кроме того, если я не использую DataBinding для макета root, он работает нормально.
Поэтому вопрос в том, что нужно добавить в 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