Search code examples
androidandroid-fragmentsandroid-activityfragment

open fragment in same activity


i have 2 activity (ActivityMain , ActivityCost) and 1 Fragment that extend Fragment (FragmentFormula) that open in ActivityMain.

how can I open FragmentFormulafrom ActivityCost?

I want ActivityMain Opened and FragmentFormula shown. I use this code, but not work.

    Intent intent = new Intent(G.context, ActivityMain.class);
    G.context.startActivity(intent);
    overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
    ActivityMain.relative_content.setVisibility(View.VISIBLE);
                    
    FragmentFormula fragmentFormula = new FragmentFormula();
    android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.frameLayout_main_Content,fragmentFormula);
transaction.commit();


Solution

  • I don't understand what you're trying to achieve.

    Here you are starting ActivityMain and then setting the fragment, this won't work because you're now in ActivityMain and not in ActivityCost anymore. Maybe what you need to do is to add the fragment in onActivityCreated of ActivityMain and not from ActivityCost after you started ActivityMain.

    If you don't want it to be the default behavior of ActivityMain you can pass an Extra in the intent and then check if it exists in ActivityMain.

    ActivityCost

    Intent intent = new Intent(G.context, ActivityMain.class);
    intent.putExtra("startFragmentFormula", true);
    G.context.startActivity(intent);
    overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
    ActivityMain.relative_content.setVisibility(View.VISIBLE);
    

    ActivityMain

    public void onActivityCreated(Bundle savedInstanceState) {
        Intent intent = getIntent();
        boolean startFragmentFormula = intent.getExtras().getBoolean("startFragmentFormula");
    
        if (startFragmentFormula) {
            FragmentFormula fragmentFormula = new FragmentFormula();
            android.support.v4.app.FragmentTransaction transaction = 
            getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.frameLayout_main_Content, fragmentFormula);
            transaction.commit();
        }
        else {
            // default behavior
        }
    }