Android RecyclerView Get Item View Width and Height

January 17, 2020
Fresco ResizeOptions in RecyclerView

I need to get Fresco’s SimpleDraweeView (which is an ImageView) actual width and height in RecyclerView.

class LocalAdapter: RecyclerView.Adapter<LocalAdapter.ViewHolder>() {

    private var resizeOptions: ResizeOptions? = null
    private var items = ...

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]

        if (resizeOptions == null) { // 1st time
            draweeView.doOnLayout { // need this to make sure draweeView.width > 0
                resizeOptions = ResizeOptions(draweeView.width, draweeView.height)
                draweeView.setImageURISize(item.uri, resizeOptions)
            }
        }
        else {
            draweeView.setImageURISize(item.uri, resizeOptions)
        }
    }
}

NOTE: View.doOnLayout is from Android KTX

fun SimpleDraweeView.setImageURISize(uri: Uri?, resizeOptions: ResizeOptions?) {
    if (uri != null) {
        val request =
            ImageRequestBuilder.newBuilderWithSource(uri)
                .setResizeOptions(resizeOptions)
                .build()
        setImageRequest(request)
    }
    else {
        setImageURI(uri as Uri?)
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.