简体   繁体   中英

How to receive (put) data from one activity to recyclerview adapter in another activity

I have an activity with tabs, in such tab - recyclerview. When i click on item in recyclerview, open another (detail) activity. In detail activity i have "favorite" button, and i want to send boolean value in adapter. My question is: how to pass data from detail activity to adapter of recyclerview. Problem is in detail activity no instance of adapter, and i not set custom listener to adapter.

I tried to implement interface

public interface OnFavoriteListener {
 void changeIcon(int position, boolean favorite);
}

and Override method onPause in detail activity

@Override
public void onPause() {
    super.onPause();
    if (mFavoriteListener != null) {
        mFavoriteListener.changeIcon(mPosition, mFavorite);            
    }
}

then implement listener in my adapter

@Override
public void changeIcon(int position, boolean favorite) {        
    mResource.get(position).setFavorite(favorite);
}

and when i return from detail activity to recyclerview nothing happens

create an application class with YourAppName

public class YourAppName extends Application {


private static YourAppName mInstance;
private static ArrayList<YourModel> source; //This is your mSourceList

 @Override
    public void onCreate() {
        super.onCreate();

        setmInstance(this); //this is a setter for mInstance value
}

 public static synchronized YourAppName getInstance() {
        return mInstance;
    }
     public static void setmInstance(YourAppName mInstance) {
        YourAppName.mInstance = mInstance;
    }

after you create this class in your app and define source value;

in your activity onCreate call this

YourAppName.getInstance().source = mSource;

and set your recyclerView adapter with YourAppName.getInstance().source not with mSource list;

then go to your detailActivity onPause()

delete old interfaceMethod and write this

YourAppName.getInstance.source.get(position).setFavorite(favorite);

when you return your Activity call adapter.notifySetDataChanged() in onResume();

it will work for you.

First, assume, when your "detail activity" popout, you click "favorite" to set a boolean value to "true". so after that, you will close your "detail activity", so when you click "favorite", you should get your recyclerView in your "main activity" and call notifyItemChanged() to set your value to "true" in your data source. You can write a "get()" method to get your recyclerView in your "main activity".

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