Getting position of View in onCreateViewHolder
You cannot use the position
parameter of onBindViewHolder
in a callback.If a new item is added above, RecyclerView will not rebind your item so the position is obsolete.Instead, RecyclerView provides a getAdapterPosition
method on the ViewHolder.
@Overridepublic ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) { final View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.single_line_row, parent, false); final ViewHolder holder = new ViewHolder(view); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int position = holder.getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { remove(mCommentList.get(position)); } } }); return holder;}
I've added position != RecyclerView.NO_POSITION
check because when item is removed, RecyclerView will fade out the View so it may still be clicked by the user but its adapter position will return NO_POSITION
.
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 }
override getItemViewType method in your Adapter:
@Overridepublic int getItemViewType(int position) { //... return position;}
Now viewType is position
@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { int position=viewType; //position //your code View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recursive, parent, false); return new ViewHolder(view); }
for example
public class BrandBtnAdapter extends RecyclerView.Adapter<BrandBtnAdapter.MyViewHolder>{ //............ @Override public int getItemViewType(int position) { //... return position; } @Override public BrandBtnAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { int position = viewType; //position final View itemView = mInflater.inflate(mResource, parent, false); return new BrandBtnAdapter.MyViewHolder(itemView); }}