Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

android - Replace fragments in 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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...