Search code examples
androidandroid-fragmentsandroid-intentandroid-activityandroid-fragmentactivity

How to go from an Activity to a specific Fragment inside a TabActivity?


I've been working on this problem now for several hours but still couldnt figure it out. I have a MainActivity with several Tabs, which are all linked to their own fragment. The Tabs and their fragments are all working perfectly fine.

Main Activity with different Tabs(Fragments): Main Activity with different Tabs(Fragments)

When I switch to the second Tab you can see a button.

MainActivity and Tab2(Fragment1): MainActivity and Tab2(Fragment1)

Through the button "Theorie" you are navigated to the SecondActivity.

SecondActivity: SecondActivity

Now there is the following problem. I would like to return to Tab2 in the MainActivity. But because this is the second fragment of the MainActivity, I always get transfered only to the first Tab "Home" in the MainActivity with the following code.

`

ImageView homebtn = (ImageView) findViewById(R.id.homebtn);
 homebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(intent);
            }
        });

`

I really don't know, how I can get through the homebtn to the second Fragment "Tab2" instead of the first Fragment "Home" in the MainActivity. When I conducted a research about this problem, I only found solutions how to transfer data from on fragment to another or how to get from the MainActivity to its fragments. I couldn't find any solutions for my specific problem.

If you have any advice for me how to solve this problem, I would be very thankful :)

Greetings Chris


Solution

  • When you are going to the Second activity, don't finish the first activity. And on home button just use this :-

    finish(); 
    

    Instead of:-

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
    startActivity(intent);
    

    You are finishing the first activity in the process and starting a new activity altogether which resets everything. Hope this helps.