Replace fragments in the FrameLayout layout

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, MainActivity
. Now I’d like to change fragments on a click in the drawer.

In my content_main
(default fragment in the MainActivity
activity), I have a framelayout that I wish to put the fragments in. I have the following fragments: fragment_main
, fragment_one
and fragment_two
. And I wish to show these when I click on a button in the nav drawer.

The reason I want to use fragments is so that the nav drawer will stay on top.

Thanks in advance!

Edit: Here is the function I’ll use to change fragments:

It’s just to test, not finished.

public void setFragment() {
    android.support.v4.app.FragmentTransaction transaction;
    transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, new LoginFragment());
    transaction.commit();
}

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.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Replace fragments in the FrameLayout layout

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录