简体   繁体   中英

Get item position of RecyclerView from another class

I have a CardView list containing around 20 cards made using RecyclerView and an Adapter .

After a Card item is clicked, I want it to start a new intent containing another CardView list. I can do this, but I also want it to set card colors depending on the card position clicked.

For example - If card item Red is clicked, it should start new intent class and set card colors to shades of Red (I can define it). And similarly with other color card items.

Is this possible?

You can simply get the position of CardView from Adapter .

This will help you.

First pass your color as a string to your new activity with bundle:

Intent mIntent = new Intent(mContext, YourNewActivity.class);
mIntent.putExtra("color", yourColorString);
startActivity(mIntent)

In your new Activity get color from bundle.

String color = "#000";
Bundle bundle = getIntent().getExtras();
if(bundle != null){
    color = bundle.getString(color,"#000");
}

Pass your color to your adapter in your adapter constructor and in adapter find your card view and set background color like below:

cardView.setBackgroundColor(Color.parseColor(color));

Good luck.

do it in this way...inside your adapter

@Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
       //..... your rest code

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context,SecondActivity.class);
                intent.putExtra("CardPosition",position); //for positiion
                intent.putExtra("CardColor",
                    list.get(position).getColor()); //for value
                context.startActivity(intent);
            }
        });
    }

in second activity you can get position of cardview...change method as per your requirement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM