简体   繁体   中英

Starting new activity from recyclerview adapter

I am reading data from firebase real time database to a recyclerview and on the recyclerview item there a button to start a new activity. I have this onClick method

public void bookBtnOnClick(final int position){
        mBookButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(this,ReservationForm.class));
                }
        });
    } 

But it cannot resolve intent constructer

而不是这个尝试mContext因为我猜你是在 Adapter 类中尝试它

  mContext.startActivity(new Intent(mContext,ReservationForm.class));

'this'改为'mContext'

mContext.startActivity(new Intent(mContext,ReservationForm.class));

try-->

Intent intent =  new Intent(context, ReservationForm.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(intent);

Adding more to @S.ambika's answer.

Change this to mContext when creating Intent .

mContext.startActivity(new Intent(mContext,ReservationForm.class));

As when you use this , it will give the current context. In your case this is returning the context of onClick and for starting a new Activity, we need the context of Activity .

try this:

public void bookBtnOnClick(final int position){
     mContext.startActivity(new Intent(context, ReservationForm.class));
} 

How's about this

Intent intent = new Intent (v.getContext(), ReservationForm.class);
v.getContext().startActivity(intent);
Define Context mContext;  on starting of adapter and in constructor use this.mcontext=mcontext;

mContext.startActivity(new Intent(mContext,ReservationForm.class));

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