0

In my app I have two fragment in ManiActivity.class . In my fragment I have a listview , when I click a item in list I open MainActivity2.class . In MainActivity2.class I have listview related and when i click list related I open MainActivity2.class with new value. Now I want create a button back home in MainActivity2.class and when I open many MainAcitivty2.class when click list related on it I can click button back home to go to MainActivity2.class I try it with

Intent intent = new Intent(MainActivity2.this,MainActivity.class)
startIntent(intent)

But when I click back button in MainActivity.class it comback MainActivity2.class , it not exit app. How I do to clear it? Please help me.

learner
  • 3,092
  • 2
  • 21
  • 33
Trần Hoà
  • 115
  • 10
  • Possible duplicate of [Override back button to act like home button](http://stackoverflow.com/questions/2000102/override-back-button-to-act-like-home-button) – Jyotman Singh Feb 18 '16 at 06:49

4 Answers4

0

Use android:launchMode="singleTask" for your MainActivity in AndroidManifest.xml.

Which will keep only one instance of MainActivity if launched again this activity will come to top of the stack. And Use this code

Intent intent = new Intent( MainActvity2.this, MyActivity.class );
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP );
current_activity.startActivity( intent );
Harsh Sharma
  • 898
  • 1
  • 14
  • 30
0

This is why Android maintains states of each activity in a Stack, that's why when you will press that Back-button, you just have to clear all previous activities from the stack and then open MainActivity

Just you have to set flags before starting intent:

Intent intent = new Intent(MainActivity2.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
Meet Vora
  • 2,783
  • 1
  • 16
  • 33
0

call finish method after startIntent

something like this:

Intent intent = new Intent(MainActivity2.this,MainActivity.class);
startIntent(intent);
finish();

and put finish method in your activity

@Override
public void finish() {
    super.finish();
}
0

its very simple.. use finish();

Intent intent = new Intent(MainActivity2.this,MainActivity.class);
startIntent(intent);
finish();

bcz u create multi activity in mainActivity2. so u have to destroy your activity before u go to mainActivty.

otherwise when u open new many in mainactivity2. that time use finish.. bcz u must have to destroy first your mainActivity2.

if you not understand my answer then just post your whole code... i will edit...

Sagar Chavada
  • 5,169
  • 7
  • 40
  • 67