从onBindViewHolder获取位置到Fragment

时间:2019-02-16 06:32:58

标签: android kotlin android-recyclerview recycler-adapter

这是我的FragmentA

enter image description here

添加图像使用户可以捕获图像并将其保存到电话外部存储中。 newListList,它从手机存储中检索所有图像,最后设置为适配器。

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

这是适配器类中的onBindViewHolder

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
        }

    }

onBindViewHolder内,我可以轻松获取图像路径

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

但是当单击片段中的滴答动作栏时如何获得位置?

 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)
    }

我一直在显示空值。

修改

适配器类这样声明

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)
    }

    .....  
}

2 个答案:

答案 0 :(得分:0)

创建界面

interface AddImageClickListener {

    fun onClick(position: Int)

}

您的适配器类将是这样

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)
        })
    }
}

在片段类中实现AddImageClickListener

然后像这样设置适配器 myRecyclerView.setAdapter(ImageListAdapter(this,newList),this)

并在AddImageClickListener的替代方法中,选择所选图像的位置

答案 1 :(得分:0)

在适配器中

override fun onBindViewHolder(holder: SideMenuAdapter.ViewHolder, position: Int) {
        holder.bindItems(arrayList.get(position))
        if (selected==position){
            holder.itemView.frame_sidemenu.setBackgroundResource(R.drawable.sidemnubg)
        }else{
            holder.itemView.frame_sidemenu.setBackgroundResource(R.color.transparent)
        }
        holder.itemView.frame_sidemenu.setOnClickListener{
            holder.itemView.frame_sidemenu.setBackgroundResource(R.drawable.sidemnubg)
            val posEvent = PosEvent()
            posEvent.pos = position
            EventBus.getDefault().post(posEvent)

        }

    }

在片段中

@Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(posEvent: PosEvent) {
        drawerLayout.closeDrawer(Gravity.LEFT)
        openFragments(posEvent.pos)
//        showToast(arrayList[position])
        selectednavPosition = posEvent.pos
        val adapter_menu: SideMenuAdapter = 
        SideMenuAdapter(this@MainActivity,arrayList,selectednavPosition)
        recycler_menu.adapter = adapter_menu
    }


override fun onResume() {
        super.onResume()
        EventBus.getDefault().register(this)
    }

    override fun onPause() {
        super.onPause()
        EventBus.getDefault().unregister(this)
    }

事件

class PosEvent{
    var pos: Int = 0
        get() = field                     // getter
        set(value) { field = value }
}