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

Categories

I'm starting with Android and in my project I'm using this BottomBar. Love it, works pretty well. The code of my application is almost identical on to the one he uses in the tutorial, the only different thing is that my MainActivity extends from AppCompatActivity.

Now what I'm trying to do is to load fragments in the FrameLayout:

<!-- This could be your fragment container, or something -->
<FrameLayout
    android:id="@+id/contentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/bottomBar"
    />

To do so I'm trying this piece of code, which I found googling for the answer of my issue:

// Create new fragment and transaction
QrCodeFragment newFragment = new QrCodeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.bottomBar, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

The line transaction.replace(R.id.bottomBar, newFragment); is complaining about the type of newFragment, which should be android.app.Fragment. My QrCode class: public class QrCodeFragment extends Fragment

As I'm starting with Android today I'm confused if I'm doing the right thing. If I should really load fragments inside the FrameLayout and if so, what am I doing wrong that I can't load it. I know it's the type of my fragment, but I don't know how to create it with the required type. I created it using Android Studio > New > Fragment > Fragment (Blank)

Thanks for any help


UPDATE: I found the solution to my error in this post but even not having the error I still can't see the fragment.

See Question&Answers more detail:os

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

1 Answer

First you have a mistake in your Fragment transaction line, according with your layout should be:

transaction.replace(R.id.contentContainer, newFragment); // not R.id.bottomBar

Second, you should use supportFragmentManager instead of fragmentManager to work with support fragments, so implement the following way:

final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.contentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...