Get position from onBindViewHolder to Fragment

2019-09-21 16:28发布

问题:

This is my FragmentA

The add image allow user to capture image and save into phone external storage. The newList is a List which retrieve all the image from phone storage and finally set to adapter.

newList = retrieveCaptureImagePath() 
myRecyclerView.setLayoutManager(
                LinearLayoutManager(
                    getActivity(),
                    LinearLayoutManager.HORIZONTAL, false
                )
            )
myRecyclerView.setHasFixedSize(true);
myRecyclerView.setAdapter(ImageListAdapter(this, newList))

This is onBindViewHolder in adapter classs

override fun onBindViewHolder(holder: ViewHolder, p1: Int) {

        context.longToast("position "+imgPics?.get(p1).toString())

        val item = this!!.imgPics?.get(p1)

        val bfOptions = BitmapFactory.Options()
        bfOptions.inDither = false                     
        bfOptions.inPurgeable =
            true                   
        bfOptions.inInputShareable =
            true             
        bfOptions.inTempStorage = ByteArray(32 * 1024)
        var fs: FileInputStream? = null

        val file = File(imgPics?.get(p1).toString())
        if (file.exists()) {
            fs = FileInputStream(File(imgPics?.get(p1).toString()))
            if (fs != null) {
                var bm = BitmapFactory.decodeFileDescriptor(fs.fd, null, bfOptions)
                holder.image?.setImageBitmap(bm)
            }
        }

        with(holder.itemView) {
            tag = item
        }

    }

Inside onBindViewHolder, I can easily get the image path

 context.longToast("position "+imgPics?.get(p1).toString())

But how can I get the position when the tick action bar in fragment is clicked?

 override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId

        if (id == R.id.save) {
            for (i in newList?.size.toString()) {
                val position = view?.tag
                longToast(position.toString())
            }
        }

        return super.onOptionsItemSelected(item)
    }

I keep getting null value displayed.

Edit

Adapter class declare like this

class ImageListAdapter(
    private val context: Fragment,
    private val imgPics: MutableList<String>?,
    private val mListener: ImageAdapterUIHandler?
) :
    RecyclerView.Adapter<ImageListAdapter.ViewHolder>() {


    private val mOnClickListener: View.OnClickListener

    init {
        mOnClickListener = View.OnClickListener { v ->
            val item = v.tag as String
            mListener?.onWorkRequestClicked(item)
        }
    }


    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
        val view = LayoutInflater.from(p0.context)
            .inflate(R.layout.grid_item, p0, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int{
        return imgPics?.size!!
    }


    override fun onBindViewHolder(holder: ViewHolder, p1: Int) {

        context.longToast("position "+imgPics?.get(p1).toString())

        val item = this!!.imgPics?.get(p1)

        val bfOptions = BitmapFactory.Options()
        bfOptions.inDither = false                     //Disable Dithering mode
        bfOptions.inPurgeable =
            true                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
        bfOptions.inInputShareable =
            true              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
        bfOptions.inTempStorage = ByteArray(32 * 1024)
        var fs: FileInputStream? = null

        val file = File(imgPics?.get(p1).toString())
        if (file.exists()) {
            fs = FileInputStream(File(imgPics?.get(p1).toString()))
            if (fs != null) {
                var bm = BitmapFactory.decodeFileDescriptor(fs.fd, null, bfOptions)
                holder.image?.setImageBitmap(bm)
            }
        }

        with(holder.itemView) {
            tag = item
//            setOnClickListener(mOnClickListener)
        }

    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val image: ImageView = itemView.imageView2
    }

    interface ImageAdapterUIHandler{
        fun onWorkRequestClicked(pos: String)
    }

}

FragmentA

class FragmentA : BaseFragment(true),ImageListAdapter.ImageAdapterUIHandler {

    override fun onWorkRequestClicked(pos: String) {
       longToast(pos)
    }

  override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_create_work_request, container, false)
        return view
    }

    @SuppressLint("ResourceAsColor")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity.hideBottomNavigation()
            ........
     }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.create_request, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId

        if (id == R.id.save) {
            for (i in newList?.size.toString()) {
                 // get the position from adapter
            }
        }

        return super.onOptionsItemSelected(item)
    }

    .....  
}

回答1:

create an interface

interface AddImageClickListener {

    fun onClick(position: Int)

}

your adapter class would be like this

class ImageListAdapter(var context: Context, var newList: ArrayList<ImageList>?,
                      var addImageClickListener: AddImageClickListener?) :
        RecyclerView.Adapter<MyViewHolder>() {

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

        holder.view.setOnClickListener({
            addImageClickListener!!.onClick(position)
        })
    }
}

implement AddImageClickListener in your fragment class

then set the adapter like this myRecyclerView.setAdapter(ImageListAdapter(this, newList),this)

and in override method of AddImageClickListener, take the position of selected image