How To Get The Edit Text Position From Recycler View Adapter Using Text Watcher In Android
I want to know how to get position of Edit Text from Recycler View adapter.I used Card View with in that horizontal Linear Layout has three view TextView,EditText view and TextVie
Solution 1:
In onBindViewHolder method of your Adapter, set tag for your EditText like this:
holder.editText.setTag(position);
And in your ViewHolder, add TextWatcher to your EditText
publicstaticclassViewHolderextendsRecyclerView.ViewHolder {
EditText editText ;
publicViewHolder(View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.editText);
MyTextWatchertextWatcher=newMyTextWatcher(editText);
editText.addTextChangedListener(textWatcher);
}
}
And here is your TextWatcher:
publicclassMyTextWatcherimplementsTextWatcher {
private EditText editText;
publicMyTextWatcher(EditText editText) {
this.editText = editText;
}
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
}
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
intposition= (int) editText.getTag();
// Do whatever you want with position
}
@OverridepublicvoidafterTextChanged(Editable s) {
}
}
NOTE: Make sure you call
setTagmethod from yourEditTextbefore callingsetTextmethod, else it will throwNullPointerException. Or alternatively you can addnullcheck when callinggetTagmethod.
UPDATE 1
If your EditText already has another tag set, use ID to identify tags. e.g. when setting tag use this:
holder.editText.setTag(R.id.editText, position);
where R.id.editText is valid id of any of your resources (See documentation for details).
And also when getting value:
int position = (int) editText.getTag(R.id.editText);
Solution 2:
Assume you use the following CustomViewHolder
publicstaticclassCustomViewHolderextendsRecyclerView.ViewHolder {
private TextView textView;
private TextView textView2;
private EditText editText;
privateint position;
publicCustomViewHolder(View view) {
super(view);
textView = (TextView) view.findViewById(R.id.text_view);
textView2 = (TextView) view.findViewById(R.id.text_view2);
editText = (EditText) view.findViewById(R.id.edit_text);
editText.addTextChangedListener(newCustomWatcher(this));
}
}
and use the following CustomWatcher
publicstaticclassCustomWatcherimplementsTextWatcher {
privateint CustomViewHolder holder;
publicCustomWatcher(CustomViewHolder holder){
this.holder = holder;
}
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
}
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
}
@OverridepublicvoidafterTextChanged(Editable s) {
}
publicintgetPosition(){
return holder.position;
}
}
Then, in your onBindViewHolder
@OverridepublicvoidonBindViewHolder(final CustomViewHolder holder, finalint position) {
holder.position = position;
}
Post a Comment for "How To Get The Edit Text Position From Recycler View Adapter Using Text Watcher In Android"