1
  • I have MainActivity with BottomNav which includes 3 Fragments A, B, and C.

  • From Fragment A, I can go to Activity A and from, Activity A I can go to Activity B.

  • Now I want to return to specifically Fragment A from Activity B by pressing a Back button while skipping Activity A.

  • I've tried Intent.FLAG_ACTIVITY_CLEAR_TASK in Activity A before starting Activity B and also explicitly starting an Intent to MainActivity from Activity B but it's not giving the result I want and of course it doesn't seem like an efficient way to do it. How do I return back to the fragment?

Vrushi Patel
  • 2,361
  • 1
  • 17
  • 30
Jason Hew
  • 13
  • 4

4 Answers4

0

Maybe it is not the ideal solution but should work

In Activity B

@Override
public void onBackPressed() {   
   Intent i = new Intent(ActivityB.this, MainActivity.class);
   i.putExtra("cameFromActivityB", true);
   startActivity(i);
 }

In Main Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    Bundle extras = getIntent.getExtras();
    if(extras.getBoolean("cameFromActivityB", false))
    {
       loadFragmentA();
    }
}
taygetos
  • 3,005
  • 2
  • 21
  • 29
Eren Tüfekçi
  • 2,463
  • 3
  • 16
  • 35
  • You can look for the ideal solution here https://stackoverflow.com/questions/5001882/how-to-clear-specific-activity-from-the-stack-history – Eren Tüfekçi Nov 09 '19 at 10:40
0

// Inside the onCreate on every Activity://

getSupportActionBar().setTitle("name of the Activity here"); 
getSupportActionBar().setDisplayHomeAsUpEnable(true);

//then go to the manifest file in //

//before that closing bracket set the order of your Activities; example (you have three activities,the Main Activity,Activity2,Activity3)//

<activity android:name=".Activity2" 
android:parentActivityName=".MainActivity"></activity>

viloria
  • 21
  • 5
0

What you can do is when you start your ActivityB from ActivityA just finish your activityA by finish() method.

Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
finish();

By doing this you will not be redirected to ActivityA instead, you will be directy redirected to your main activity when you press back button from your activityB.

Chirag Parekh
  • 102
  • 2
  • 7
0

Case 1

You need to finish Activity A after launching intent.

Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
finish(); 

case 2

If you want to come back on Activity A at some point then what you need is passing some flag from Activity B to A. And run this code at the beginning of your activity A.

if(extras.getBoolean("NameOfFlag", false))
    {
       ActivityA.finish();
    }

send flag by using this code.

Intent i = new Intent(ActivityB.this, ActivityA.class);
i.putExtra("NameOfFlag", true);
startActivity(i);
finish();

Remember to finish() Activity when you don't need to come back. In this case ActivityB .

Vrushi Patel
  • 2,361
  • 1
  • 17
  • 30