2.6的RecyclerView onItemClick界面被触发两次

时间:2016-09-10 18:15:07

标签: android android-recyclerview

我为OnItemClickListener实施了RecyclerView。它正在工作,我在活动中得到了recyclerview中行的文本,但问题是我的public void rvOnClick(View view, int position)中的函数MyActivity.class被称为两次。我不明白为什么,我只希望每行选择/点击一次。

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();
}
}

1 个答案:

答案 0 :(得分:0)

删除 itemListener.rvOnClick(v, getLayoutPosition());

实际上你是两次打电话。将你的方法改为此。

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