Search code examples
androidandroid-activityandroid-loadermanager

Android Activity ListView LoaderManager Navigation with remembering previous state


I have my launcher activity which generates a ListView.

Now on the ListView I have a setOnItemClickListener which will basically pass the position and the id to a new activity.

mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(ActivityHome.this, ActivityDetail.class);
            intent.putExtra("cm_position", position);
            intent.putExtra("cm_id", id);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    });

Now the ListView in ActivityHome is showing somewhere in the middle of the ListView.

When I am in the ActivityDetail, and I have a actionBar.setDisplayHomeAsUpEnabled(true); so when the below is executed it will go back to ActivityHome

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent intent = new Intent(this, ActivityHome.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

The problem is the position in the ListView is lost and the ListView goes back to the top. Is there a way to stop onCreate() from executed and just destory the Activity for ActivityDetail and just move back to ActivityHome to what it was... I hope you understand.

I think I may have set the flags wrong for the intent...


Solution

  • Fixed:

    In the ActivityDetail, you need to set this flag

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
    

    I knew it was something to do with using flags properly!!!

    The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().