Anant Singh Anant Singh - 4 months ago 27
Android Question

Finish the fragment while moving to other activity?

I have a main activity that contains 3

fragments
. In each
fragment
I have a
listView
, on clicking which it is diverted to a new activity.

In the new
Activity
, I am changing the list view content that is clicked and diverting back to the main activity using intent.

This opens a new main Activity fragment and when I press back button I again get back to the previous Main Activity that was opened earlier.

Answer

Save activity's context in static variable like this

 public class MainActivity extends AppCompatActivity {
        public static MainActivity mainActivity;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_staff_login);
            //finishing older loaded mainActivity 
            if(MainActivity.mainActivity!=null){
               MainActivity.mainActivity.finish();
            }
            mainActivity=this;

        }
    }

From other activities you can finish your older activity like this

if(MainActivity.mainActivity!=null){
     MainActivity.mainActivity.finish();
   }
Comments