user1406716 user1406716 - 2 months ago 25
Android Question

Interface for onItemClick of RecyclerView getting triggered twice

I have implemented like an

OnItemClickListener
for
RecyclerView
. It is working and I get the text for the row in the recyclerview back in the Activity but the problem is that the function
public void rvOnClick(View view, int position)
in my
MyActivity.class
gets called twice. I dont understand why, i only want it to be called once on each row select/click.

MyActivity.class:

public class MyActivity extends AppCompatActivity
implements RecyclerViewClickListener {


@Override
public void rvOnClick(View view, int position) {
mLog.printToLog("Clicked User (from Activity) : " + selAppsList.get(position).getAppname());
}
}


RecyclerViewClickListener.class:

import android.view.View;

public interface RecyclerViewClickListener {

public void rvOnClick(View view, int position);
}


Adapters_SelectApps.class:

public class Adapters_SelectApps extends RecyclerView.Adapter<Adapters_SelectApps.MyViewHolder> {

private List<Model_SelectApps> selAppsList;
private MyAppLogger mLog = new MyAppLogger();

private Context context;
private RecyclerViewClickListener itemListener;

public class MyViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
public TextView tv_selappname;
public ImageView iv_selappicon;
public CheckBox cb_selappcheckbox;

private String mItem;

public MyViewHolder(View view) {
super(view);
tv_selappname = (TextView) view.findViewById(R.id.tv_selappname);
view.setOnClickListener(this);
}

public void setItem(String item) {
mItem = item;
tv_selappname.setText(item);
}

@Override
public void onClick(View v) {
itemListener.rvOnClick(v, getLayoutPosition());

if(itemListener != null) {
itemListener.rvOnClick(v, getAdapterPosition());
}
}

}


public Adapters_SelectApps(Context context,
List<Model_SelectApps> selAppsList) {
this.context = context;
this.selAppsList = selAppsList;
}

public void setClickListener(RecyclerViewClickListener rvItemClickListener) {
this.itemListener = rvItemClickListener;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_selappslist, parent, false);

return new Adapters_SelectApps.MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Model_SelectApps app = selAppsList.get(position);
holder.tv_selappname.setText(app.getAppname());
}

@Override
public int getItemCount() {
return selAppsList.size();
}
}

Answer

remove itemListener.rvOnClick(v, getLayoutPosition());

actually you are calling it twice. change your method to this.

@Override
    public void onClick(View v) {
        if(itemListener != null) {
            itemListener.rvOnClick(v, getAdapterPosition());
        }
    }