简体   繁体   English

从另一个类获取RecyclerView的项目位置

[英]Get item position of RecyclerView from another class

I have a CardView list containing around 20 cards made using RecyclerView and an Adapter . 我有一个CardView列表,其中包含约20张使用RecyclerViewAdapter制作的Adapter

After a Card item is clicked, I want it to start a new intent containing another CardView list. 单击Card项目后,我希望它启动包含另一个CardView列表的新intent 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). 例如-如果单击卡片项目Red ,它将开始新的意图类别,并将卡片颜色设置为Red阴影(我可以定义它)。 And similarly with other color card items. 并与其他色卡项目类似。

Is this possible? 这可能吗?

You can simply get the position of CardView from Adapter . 您可以简单地从Adapter获取CardView的位置。

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 在第二个活动中,您可以获取cardview的位置...根据您的要求更改方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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