i want to implement on onclicklistener on cardview and every card takes me to a different activity

只愿长相守 提交于 2019-12-25 18:52:07

问题


I want to replace the toast and I want every card view when clicked takes the user to a new different activity. I would also like to implement Interstitial ads when the user clicks on the cardview.

Here is my adapter class

public class MyAdapter extends RecyclerView.Adapter< LessonViewHolder > {

private Context mContext;
private List< LessonData > mLessonList;

MyAdapter(Context mContext, List< LessonData > mLessonList) {
    this.mContext = mContext;
    this.mLessonList = mLessonList;
}

@Override
public LessonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_row,  parent, false);
    return new LessonViewHolder(mView);
}

@Override
public void onBindViewHolder(final LessonViewHolder holder, int position) {
    holder.mImage.setImageResource(mLessonList.get(position).getLessonImage());
    holder.mTitle.setText(mLessonList.get(position).getLessonName());

    holder.mCardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

         // I want every single card takes the user to a new different activity, and also implement interstitial ads when the user clicks
        }
    });
}




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

class LessonViewHolder extends RecyclerView.ViewHolder {

CardView mCardView;
ImageView mImage;
TextView mTitle;

LessonViewHolder(View itemView) {
    super(itemView);

    mImage = itemView.findViewById(R.id.ivImage);
    mTitle = itemView.findViewById(R.id.tvTitle);
    CardView mCardView = itemView.findViewById(R.id.cardview);
}
}

I also want to ad Interstitial ads when the user clicks on these card.


回答1:


You will want to set a click listener on each element in your list.

Inside your onBindViewHolder write something like this:

 holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(pos == 0){              
               view.getContext().startActivity(new Intent(view.getContext(),Activity1.class));
           }else if(pos == 1){
               view.getContext().startActivity(new Intent(view.getContext(),Activity2.class));
          }
        }
    });
}

Happy Coding ;)



来源:https://stackoverflow.com/questions/53802048/i-want-to-implement-on-onclicklistener-on-cardview-and-every-card-takes-me-to-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!