Android: How do I return to newly created RecyclerView list?

痞子三分冷 提交于 2019-12-02 18:15:42

问题


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();
    }
});    

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!