Getting position of View in onCreateViewHolder

前端 未结 3 1609
野性不改
野性不改 2020-12-15 06:29

I am using a RecyclerView with a single row layout with an ImageView and a TextView.

I want to implement a OnClickListener for the View and not for seperate ViewHold

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 06:59

    you can create a method to update position in your class.

    in my case I need to attach watcher and get the position to update arraylist. here is the example:

    class DodolWatcher bla bla {
        private var position: Int = 0
        fun updatePosition(pos:Int)
        {
          position = pos
        }
    
        override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
        Log.d("test", position.toString())
        }
    
    }
    

    and in your onCreateViewHolder you can attach watcher to edittext

     override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RVPaymentMethodAdapter.ViewHolder {
         ....
         bla bla
         ....
         theWatcher = DodolWatcher() <-- this is the trick
         amount.addTextChangedListener(theWatcher)
     }
    

    and you will able to update position in your bindViewHolder like this:

    override fun onBindViewHolder(viewHolder: RVPaymentMethodAdapter.ViewHolder, position: Int) {
         theWatcher.updatePosition(viewHolder.adapterPosition)  <-- this is the trick
     }
    

提交回复
热议问题