I create a RecyclerView list with a default layout. I then add one new item to the list and the layout updates to show the new item. I then navigate to a previous activity. When I return to the RecyclerView activity I am returned to the generic, default list and my new item in the RecyclerView list is gone.
So how do I return to the RecyclerView and the new item that I created rather than the generic list? Do I need to add some code that says if the size of the adapter is > 0 then don't create a new list use the existing one? And should I be doing the test in the RecyclerView activity or in the adapter? If not, does my issue arise because the adapter is not related somehow to the savedInstanceState of the RecyclerView activity?
Activity:
public class ListContactsActivity extends AppCompatActivity {
private ListContactsAdapter mContactsAdapter;
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclerviewlist);
final List<Contact> mContacts;
mContacts = new ArrayList<>();
mRecyclerView = (RecyclerView) findViewById(R.id.cardList);
mRecyclerView.setLayoutManager(getLayoutManager());
mRecyclerView.setHasFixedSize(true);
mContactsAdapter = new ListContactsAdapter(this, mContacts);
mRecyclerView.setAdapter(mContactsAdapter);
...
}
private RecyclerView.LayoutManager getLayoutManager() {
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
return llm;
}
Adapter:
class ListContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
@Override
public int getItemCount() {
return mItems.size();
}
Toolbar code in Activity:
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_action_previous_item);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
When you hit back from an activity you are popping it from the stack i.e the activity object will be destroyed. This is explained in further detail here. The crux of the concept can be understood from this picture.
You can look at this to see how you should recreate your activity - and this to see how you should apply that to a recyclerview.
来源:https://stackoverflow.com/questions/35413495/android-how-do-i-return-to-newly-created-recyclerview-list