Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch activity and show specific fragment

I have a MainActivity that has several fragments which are added and then shown/hidden. This is because the MainActivity uses a NavigationDrawer. Clicking on items in the drawer causes different fragments to be added (if they do not exist), or shown/hidden if they do.

My question is, how can I launch my MainActivity via an intent from a different activity, and at the same time show a specific fragment?

Would I have to pass some extra to my MainActivity and then based on that data, add/show/hide the relevant fragment? Is there another way?

like image 916
Micro Avatar asked Mar 17 '16 14:03

Micro


People also ask

How can we set one fragment in activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

Can you call an activity from a fragment?

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.


2 Answers

When you create your Intent, you can give it an extra that determines the fragment to load.

Intent i = new Intent(this, ActivityClass.class);
i.putExtra("frgToLoad", FRAGMENT_A);

// Now start your activity
startActivity(i);

Now, inside your activity check the extra and load the right Fragment:

OnCreate(){
    ...

    int intentFragment = getIntent().getExtras().getInt("frgToLoad");

    switch (intentFragment){
        case FRAGMENT_A:
            // Load corresponding fragment
            break;
        case FRAGMENT_B:
            // Load corresponding fragment
            break;
        case FRAGMENT_C:
            // Load corresponding fragment
            break;
    }
}
like image 146
Bad Toro Avatar answered Nov 11 '22 19:11

Bad Toro


You can use sharedPreference to achieve the goals. Save the index after you open you TAB/Fragment.

        //get current tab
        sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
        String position = sharedPreferences.getString("tab_opened", null);
        if(position==null){
            viewPager.setCurrentItem(1,true);
        }else if(position=="0"){
            viewPager.setCurrentItem(0,true);
        }else if(position=="1"){
            viewPager.setCurrentItem(1,true);
        }else if(position=="2"){
            viewPager.setCurrentItem(2,true);
        }

}// <<<~~~ THAT IS END OF onCreate() method.

Please refer to this tutorial : OPEN THIS .

like image 34
Sen Avatar answered Nov 11 '22 19:11

Sen