You have to iterate throughout the ViewGroup and get the ImageView based on ViewPager's current Item .
Your ViewHolder should look like this (This consist of DataBinding) . Here tags are set in the init block and pageNum of the currentItem is set as a global variable which will be used for getting the ImageView . The pageNumber function returns the pageNumber of the current item and imageView function returns the ImageView.
class EditViewHolder(val binding: RecyclerViewEditLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
private var pageNum: Int = -1
init {
binding.root.tag = this
}
fun bind(item: DataModel, pageNum: Int) {
this.pageNum = pageNum
Glide.with(binding.editImageView)
.load(item.uri)
.into(binding.editImageView)
}
fun getImageView(): ImageView {
return binding.editImageView
}
fun getPageNum(): Int {
return this.pageNum
}
}
Now in your Fragment / Activity , you need to create two functions which are
getViewHolderForItem() and getViewForItem() , these functions are as follows .
This function which is getViewHolderForItem() returns the ViewHolder
private fun getViewHolderForItem(i: Int): EditViewHolder? {
var obj: Any? = null
if (getViewForPage(i) == null) {
return null
}
val viewForPage = getViewForPage(i)
if (viewForPage != null) {
obj = viewForPage.tag
}
return obj as EditViewHolder?
}
This function below which is getViewForItem returns the particular view
private fun getViewForPage(i: Int): View? {
if (binding.editViewPager.size >= i) {
val childAt: View = binding.editViewPager.getChildAt(0)
val viewGroup: ViewGroup = childAt as ViewGroup
val childCount: Int = viewGroup.childCount
for (i2 in 0 until childCount) {
val childAt2: View? = viewGroup.getChildAt(i2)
if (childAt2 != null) {
val tag = childAt2.tag
if ((tag as EditViewHolder).getPageNum() == i) {
return childAt2
}
}
}
}
return null
}
And then you can make use of this in the following manner for getting the current bitmap of the ViewPager
val viewHolder = getViewHolderForPage(binding.editViewPager.currentItem)
val bitmap = viewHolder?.getImageView()?.drawable?.toBitmap()
And for setting the bitmap back to the ViewPager
viewHolder.getImageView().setImageBitmap(bitmap)