Replace fragments in FrameLayout layout

前端 未结 4 1333
情话喂你
情话喂你 2020-12-17 08:29

I have tried every tutorial on the first google page about android fragments, but I can\'t get anything to work.

So I have one navigation bar activity, MainAct

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 08:47

    I solved it!

    Apparently, I had to use android.support.v4.app.Fragment; instead of android.app.Fragment;. This is the code I got it to work with:

    protected void setFragment(Fragment fragment) {
        android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
        t.replace(R.id.fragment_container, fragment);
        t.commit();
    }
    

    And to set it (from the nav bar onNavigationItemSelected(), you do this:

    setFragment(new RoosterFragment());
    

    I hope this helps others out with the same frustrating problem.

提交回复
热议问题