Start a fragment via Intent within a Fragment

前端 未结 4 1416
旧巷少年郎
旧巷少年郎 2020-11-29 03:10

I want to launch a new fragment to view some data. Currently, I have a main activity that has a bunch of actionbar tabs, each of which is a fragment. So, within a tab fragme

相关标签:
4条回答
  • 2020-11-29 03:32

    You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

    So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.

    0 讨论(0)
  • 2020-11-29 03:35

    The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...

    Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.

    @Override
    public void onClick(View v) {
        // Create new fragment and transaction
        Fragment newFragment = new chartsFragment(); 
        // consider using Java coding conventions (upper first char class names!!!)
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
    
        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);
    
        // Commit the transaction
        transaction.commit(); 
    }
    

    http://developer.android.com/guide/components/fragments.html#Transactions

    0 讨论(0)
  • 2020-11-29 03:42

    Try this it may help you:

    private void changeFragment(Fragment targetFragment){
    
        getSupportFragmentManager()
             .beginTransaction()
             .replace(R.id.main_fragment, targetFragment, "fragment")
             .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
             .commit();
    
    }
    
    0 讨论(0)
  • 2020-11-29 03:45

    Try this it may help you:

    public void ButtonClick(View view) {
        Fragment mFragment = new YourNextFragment(); 
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
    }
    
    0 讨论(0)
提交回复
热议问题