如何将点击侦听器添加到RecyclerView项目

时间:2018-12-23 18:36:13

标签: android android-recyclerview

我确实在Stack上找到了很多帖子,这似乎是最好的选择,但是所选答案只有部分。 这是链接:RecyclerView onClick

您可以看到最上面的答案:

private final OnClickListener mOnClickListener = new MyOnClickListener();

@Override
public MyViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.myview, parent, false);
    view.setOnClickListener(mOnClickListener);
    return new MyViewHolder(view);
}

然后是onClick方法:

@Override
public void onClick(final View view) {
    int itemPosition = mRecyclerView.getChildLayoutPosition(view);
    String item = mList.get(itemPosition);
    Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
}

但是这个onClick在哪里?在单独的文件中?在活动中使用适配器?如果在单独的文件中,它将实现什么?您能帮我使这个答案更完整吗?

3 个答案:

答案 0 :(得分:0)

好问题..我也花了一点时间来:) 因此,IAM将向您发布回收站适配器代码,以了解在何处定义onClick 以及一个活动,了解如何实现点击。.

适配器

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {

private Context mContext;
private List<Items> mItemsArrayList;
private ItemClickListener mClickListener;
private ItemLongClickListener mLongClickListener;


public ItemAdapter(Context context, List<Items> arrayList) {
    mContext = context;
    mItemsArrayList = arrayList;
}

@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View view = inflater.inflate(R.layout.lists_list_item, parent, false);
    return new ItemAdapter.ItemViewHolder(view);
}

@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {

    holder.itemName.setText(mItemsArrayList.get(position).getName());
    int state = mItemsArrayList.get(position).getState();
    final String category = mItemsArrayList.get(position).getCategory();
    if (state == 0) {
        holder.container.setBackgroundColor(mContext.getResources().getColor(R.color.white_color));
        holder.itemName.setTextColor(mContext.getResources().getColor(R.color.colorPrimaryDark));
        holder.stateColor.setBackgroundColor(mContext.getResources().getColor(R.color.white_color));
        holder.check.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_check_gray_24dp));
    } else if (state == 1) {
        holder.container.setBackgroundColor(mContext.getResources().getColor(R.color.light_gary));
        holder.itemName.setTextColor(mContext.getResources().getColor(R.color.gray));
        holder.check.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_check_black_24dp));
        switch (category) {
            case "Auto":
                holder.stateColor.setBackgroundColor(mContext.getResources().getColor(R.color.purble));
                break;
            case "Bills":
                holder.stateColor.setBackgroundColor(mContext.getResources().getColor(R.color.light_purple));
                break;
            case "Health":
                holder.stateColor.setBackgroundColor(mContext.getResources().getColor(R.color.light_blue));
                break;
            case "Shop":
                holder.stateColor.setBackgroundColor(mContext.getResources().getColor(R.color.green));
                break;
            case "Travel":
                holder.stateColor.setBackgroundColor(mContext.getResources().getColor(R.color.orange));
                break;
            case "Work":
                holder.stateColor.setBackgroundColor(mContext.getResources().getColor(R.color.dark_blue));
                break;
        }
    }

}

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

// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
    this.mClickListener = itemClickListener;
}

public void setLongClickListener(ItemLongClickListener itemLongClickListener) {
    this.mLongClickListener = itemLongClickListener;
}

// return data
public String getItemName(int id) {
    return mItemsArrayList.get(id).getName();
}

// parent activity will implement this method to respond to click events
public interface ItemClickListener {
    void onItemClick(View view, int position);
}

public interface ItemLongClickListener {
    void onItemLongClick(View view, int position);
}

public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

    public LinearLayout container;
    public LinearLayout stateColor;
    public ImageView check;
    public TextView itemName;

    public ItemViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);

        container = (LinearLayout) itemView.findViewById(R.id.lists_item_container);
        stateColor = (LinearLayout) itemView.findViewById(R.id.lists_item_state_color);
        check = (ImageView) itemView.findViewById(R.id.lists_item_check);
        itemName = (TextView) itemView.findViewById(R.id.lists_item_name);
    }

    @Override
    public void onClick(View view) {
        if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());

    }

    @Override
    public boolean onLongClick(View view) {
        if (mLongClickListener != null) {
            mLongClickListener.onItemLongClick(view, getAdapterPosition());
            return true;
        } else {

            return false;
        }
    }
}

}

活动

public class ListsActivity extends AppCompatActivity implements ItemAdapter.ItemClickListener, ItemAdapter.ItemLongClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lists_layout);

    usersDbHelper = new MyUsersDbHelper(this);

    switch (keyCategory) {
        case "":
            goNext(keyCategory);
            break;
        case "Auto":
            goNext(keyCategory);
            break;
        case "Bills":
            goNext(keyCategory);
            break;
        case "Health":
            goNext(keyCategory);
            break;
        case "Shop":
            goNext(keyCategory);
            break;
        case "Travel":
            goNext(keyCategory);
            break;
        case "Work":
            goNext(keyCategory);
            break;
    }
}


private void goNext(final String category) {

    if (guide.equals("")) {

        title.setText("Lists");

        // Find and set empty view on the recycler View, so that it only shows when the list has 0 items.

        emptyView = (RelativeLayout) findViewById(R.id.lists_empty_view);

        // Find the Recycler View which will be populated with the event data
        itemsListView = (RecyclerView) findViewById(R.id.lists_recycler);
        itemsListView.addItemDecoration(new DividerItemDecoration(itemsListView.getContext(), DividerItemDecoration.VERTICAL));
        itemsListView.setLayoutManager(new LinearLayoutManager(this));

        // List<Items> to populate recycler View
        itemsList = usersDbHelper.readItemsList(username);
        if (itemsList.size() == 0) {
            itemsListView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        } else {
            itemsListView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
        }
        eItemAdapter = new ItemAdapter(this, itemsList);
        eItemAdapter.setClickListener(this);
        eItemAdapter.setLongClickListener(this);
        eItemAdapter.notifyDataSetChanged();
        itemsListView.setAdapter(eItemAdapter);

        search = (ImageView) findViewById(R.id.lists_item_search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCustomSearchDialog(ListsActivity.this, itemsList);
            }
        });


        listNumber = (TextView) findViewById(R.id.lists_item_num);
        listNumber.setText(String.valueOf(itemsList.size()));
    }

}

// CLICKS HERE
@Override
public void onItemClick(View view, int position) {

    usersDbHelper = new MyUsersDbHelper(this);
    String name = itemsList.get(position).getName();
    int state = itemsList.get(position).getState();
    String username = itemsList.get(position).getUsername();
    if (state == 0) {
        usersDbHelper.updateItemState(username, name, 1);
        itemsList.get(position).setmState(1);
        eItemAdapter.notifyItemChanged(position);
    } else if (state == 1) {
        usersDbHelper.updateItemState(username, name, 0);
        itemsList.get(position).setmState(0);
        eItemAdapter.notifyItemChanged(position);
    }


}

@Override
public void onItemLongClick(View view, int position) {
    showCustomDeleteDialog(ListsActivity.this, position);
}

}

希望对您有所帮助:) 快乐编程

答案 1 :(得分:0)

我们使用OnItemClickListener接口提供列表中项目的位置。默认情况下,recyclerView没有此接口。

在适配器中添加此接口

public interface OnItemClickListener {
    void onItemClick([your params]);
}

定义一个变量

private OnItemClickListener listener;

添加设置方法

public void setOnItemClickListener(OnItemClickListener listener) {
    this.listener = listener;
}

现在恢复活动或片段,输入adapter.setOnClickItemListener(new [ctrl+tab])

你应该像这样

adapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
     @Override
     public void onItemClick([Your params]) {

     }
});

另一种方式;在您的适配器中,您的Holder类的构造函数

public Holder(View itemView){
   super(itemView);

   itemView.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {

        // bla bla
       }
   });
}

答案 2 :(得分:0)

如果在recyclerView中有例如按钮,则应像这样定义两个侦听器

public interface OnItemClickListener {
    void onItemClick(int position);
    void onShareClick(int position);
}

您的此类持有人类的构造函数

public Holder(View itemView, final OnItemClickListener listener) {
        super(itemView);
        mshareButton = itemView.findViewById(R.id.iv_share);

        // listener for whole item
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               listener.onItemClick(position);
            }
        });
        // listener for button inside item
        mShareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               listener.onShareClick(position);

            }
        });
    }

然后返回“活动”或“片段”。你应该像这样

adapter = new RecyclerViewAdapter(this, arrayList);
    ((RecyclerViewAdapter) adapter).setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
                Toast.makeText(getApplicationContext(), "whole item", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onShareClick(int position) {
            Toast.makeText(getApplicationContext(), "share", Toast.LENGTH_SHORT).show();
        }
    });