How to get value from RecycleAdapter and set to MainActivity Text?

Viewed 684

My Adapter Code looks like :

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        GetSet getSet = allData.get(position);
        holder.tvId.setText(getSet.getId().toString());
        holder.tvName.setText(getSet.getName());

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.tvId)
        TextView tvId;

        @BindView(R.id.tvName)
        TextView tvName;

I have textview in MainActivity, my question is how to get value/text id and name to set in textview?

3 Answers

Suppose you have label in Activity and you wanted to pass the updated string to Activity. See the following suggestion

Adapter

//create an interface in adapter
public interface LabelChangeListener {
    void onLabelChanged(String text);
}

//create a method inside adapter
public void setLabelChangeListener(LabelChangeListener listener) {
    this.listener = listener;
}

//optional: create this method inside adapter
public void updateActivityLabel() {
    if (listener != null) {
        listener.onLabelChanged("this is update");
    }
}

Activity

//from activity 
adapter.setLabelChangeListener(new LabelChangeListener() {
    void onLabelChanged(String text) {
        lblYourTextView.setText(text);
    }
});

If you want to get Id or name of an Item on Recyclerview You can write a public function in Adapter Code like this:

public GetSet getGetSetItem(int position){
  return allData.get(position);
}

Then you call in MainActivity like this: adapter.getGetSetItem(1).getId(); or adapter.getGetSetItem(1).getName();

One more thing, you can use an api of recycler view to retrieve view holder item:

findViewHolderForAdapterPosition(position)
Related